在JavaScript中,常用offset、scroll和client家族属性来表示元素的位置和大小相关属性,最近在网上找到了一张图来表示三者之间的关系,正好可以在此借鉴一下。
本次主要来看一下offset家族,包括offsetWidth、offsetHeight、offsetLeft和offsetTop。
offsetWidth和offsetHeight
offsetWidth和offsetHeight表示的是元素的可见宽度和高度,与元素有没有设置宽高没有直接关系,并且offsetHeight = 内容 + 内边距 + 边框(宽度同理)。
在说到offsetWidth和offsetHeight的时候,就不能忽略了style.width和style.height了,这两个表示的是通过行内元素设置的元素宽高。
例1:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> #box{ background-color: red; padding: 10px; border: 5px solid #ddd; margin: 10px; } </style> </head> <body> <div id="box"></div> <script> var box = document.getElementById("box"); console.log( box.offsetWidth, box.offsetHeight); console.log( box.style.width, box.style.height);</script> </body> </html>
此时我们可以看到,因为虽然没有直接设置宽高,但元素有padding和border,所以有可见的宽高。但是因为没有设置行内宽高,所以元素的style.width和style.height为空。
例2:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> #box{ width: 200px; height: 150px; background-color: red; padding: 10px; border: 5px solid #ddd; margin: 10px; } </style> </head> <body> <div id="box" style=" 100px;height: 100px;"></div> <script> var box = document.getElementById("box"); console.log( box.offsetWidth, box.offsetHeight); console.log( box.style.width, box.style.height); </script> </body> </html>
此时,我们将例1的代码少做修改,同时设置了两次宽高,最后发现行内的宽高覆盖了样式表里设置的宽高,offset的值是在style的值上面加上了padding和border的结果,另外。offsetWidth和offsetHeight得到的是不带单位的数值,而style.width和style.height得到的是带单位的结果。
例3:
我们继续修改上面的代码,将例2中的js部分改为下面部分:
<script>
我们通过分别offsetWidth和style.width为元素赋予样式,只有style.width生效了,也就是说,offsetWidth和offsetHeight是只读的,style.width和style.height是可读写的。
offsetLeft和offsetTop
offsetLeft和offsetTop表示的是距离父元素的距离,具体值的是从符标签的padding开始计算,不包括border,即从子盒子边框到定位父盒子边框的距离。
例1:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; list-style: none; } #father{ width: 400px; height: 400px; background-color: red; margin: 40px; } #box{ width: 200px; height: 150px; background-color: blue; padding: 10px; border: 5px solid #000; margin-left: 20px; } </style> </head> <body> <div id="father"> <div id="box"></div> </div> <script> var box = document.getElementById("box"); console.log(box.offsetLeft); console.log(box.offsetTop); </script> </body> </html>
此时因为#box的父元素是没有定位的,所以获取到的知识一层层寻找有定位的上一层级,直到找到body,本次指的就是距离body的值。
现在,我们将上面的代码稍作调整,只需要修改#father的样式如下即可。
例2:
#father{
400px;
height: 400px;
background-color: red;
margin: 40px;
position: relative;
}
由例2我们可以看到,当元素的父级元素有了定位属性后,该元素的offsetLeft和offsetTop表示的就是到父元素的距离。
当然还有style.left和style.top,这里就不再详细介绍了,直接给出两者的不同之处:
-
style.left只能获取行内的,而offsetLeft则可以获取到所有的;
-
offsetLeft 可以返回没有定位盒子距离左侧的位置;而style.left不可以,其只能返回有定位盒子的left;
-
offsetLeft 返回的是数字,而 style.left 返回的是字符串,除了数字外还带有单位:px;
-
offsetLeft是只读的,而style.left是可读写;
-
如果没有给 当前 元素指定过 top 样式,则 style.top 返回的是空字符串。