源代码:
下载代码
点击运行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> <style> #myDIV { height: 250px; width: 400px; padding: 10px; margin: 15px; border: 5px solid red; background-color: lightblue; overflow: auto; } #myDIV2 { height: 250px; width: 400px; padding: 10px; margin: 15px; border: 5px solid red; background-color: lightblue; } #content { height: 800px; width: 2000px; background-color: lightyellow; } </style> </head> <body> <p>在这个实例中,子 div 元素 (#content) 插入到第一个 div 中,由子 div 元素 比第父 div元素 (#myDIV) 大, (子元素为 800x2500 ,父元素为 250x400), 所以我们使用了滚动条。</p> <p>点击按钮获取 div 元素的 clientHeight, offsetHeight, clientWidth 和 offsetWidth 属性值。</p> <button onclick="myFunction()">点我</button> <p>请注意父 div 中的滚动条“得到”子 div 的右侧和底部内边距(padding),这导致父 div 中 clientHeight 和 clientWidth 的返回值低于另一个,而 offsetHeight 和 offsetWidth 不受此影响。 <div id="myDIV"> <div id="content"></div> </div> <div id="myDIV2"> <div id="content2"></div> </div> <script> function myFunction() { var elmnt = document.getElementById("myDIV"); var txt = ""; txt += "<b>div 的样式信息:</b><br>"; txt += "高度包含内边距(padding): " + elmnt.clientHeight + "px<br>"; txt += "高度包含内边距(padding)、边框(border)及滚动条: " + elmnt.offsetHeight + "px<br>"; txt += "宽度包含内边距(padding): " + elmnt.clientWidth + "px<br>"; txt += "宽度包含内边距(padding)、边框(border)及滚动条: " + elmnt.offsetWidth + "px"; document.getElementById("content").innerHTML = txt; var elmnt2 = document.getElementById("myDIV2"); var txt2 = ""; txt2 += "<b>div2 的样式信息:</b><br>"; txt2 += "高度包含内边距(padding): " + elmnt2.clientHeight + "px<br>"; txt2 += "高度包含内边距(padding)和边框(border): " + elmnt2.offsetHeight + "px<br>"; txt2 += "宽度包含内边距(padding): " + elmnt2.clientWidth + "px<br>"; txt2 += "宽度包含内边距(padding)和边框(border): " + elmnt2.offsetWidth + "px"; document.getElementById("content2").innerHTML = txt2; } </script> </body> </html>
运行结果: