对HTML初学者来说,很多人对css中盒模型的理解不够透彻导致在javascript学习时对dom元素的clientheight,offsetheight,scrollheight等几个高度的概念混淆不清,不知道何时使用cliengheight,何时使用offsetheight,何时使用scrollheight等。今天熊老师就来聊一聊dom操作中的这几个“height”。
注意:本文以Chrome浏览器为基础进行讲解,在不同的浏览器下可能会有所差异,但原理基本相同
首先,看一个元素典型的盒模型,如下图:
在盒模型中,有如下几个概念:
margin:该属性决定当前元素和其它元素之间上下左右的距离,在上图中,该值为15px.
border:边框的宽度,在上图中,该值为5px
padding:元素内容与边框之间的距离,如上图所示,该值为10px
内容定义高度:元素内容的高度。在上图中,元素内容为250px
在html页面中,有时候元素还会有一个滚动条(scroll)出现,滚动条也会占用一定的空间,如下图:
在上面的基础之上我们列出如下公式:
clientheight=内容定义高度+paddingtop+paddingbottom-scrollerheight(滚动条高度),在图1所示的盒模型中,
在图形没有滚动条时,offsetheight=250+10+10=270
在有滚动条时:offsetheight=250+10+10-15(滚动条的高度)=255
offsetheight=内容定义高度+paddingtop+paddingbottom+bordertop+borderbottom
在图形没有滚动条时,offsetheight=250+10+10+5+5=280
在有滚动条时:offsetheight=250+10+10+5+5=280
接下来就是scrollheight,在css样式中,可以设置元素 overflow:scroll;即当元素内容的高度大于其定义的高度时将出现滚动条。如下图所示:
在上图中,如果要看到该元素更多的内容时需要向下拉动滚动条才可以看到其完整的内容,那么该元素有多高呢?这个高度就是scrollheight。
scrollheight=元素实际高度+paddingtop+paddingbottom
以上就是对javascript中几个高度的讲解,下面附上测试代码,有兴趣的同学可以自己上机实验哦。
#myDIV {
height: 250px;
width: 400px;
padding: 10px;
margin: 15px;
border: 5px solid red;
background-color: lightblue;
overflow:scroll/* 添加或删除该行即可看到或隐藏滚动条*/
}
Click the button to get the height and width of div, including padding (using both clientHeight and clientWidth).
Try it
Information about this div:
Height: 250px
Width: 400px
padding: 10px
margin: 15px
border: 5px
function myFunction() {
var elmnt = document.getElementById("myDIV");
var txt = "Height including padding: " + elmnt.clientHeight + "px
";
txt += "Width including padding: " + elmnt.clientWidth + "px
";
txt+="offsetheight:"+elmnt.offsetHeight+"px
";
txt+="scrollheight:"+elmnt.scrollHeight+"px
";
document.getElementById("demo").innerHTML += txt;
}
领取专属 10元无门槛券
私享最新 技术干货