element.offsetLeft
与element.style.left
的区别
-
element.offsetLeft
- 只读值
- 返回当前元素左上角相对于
offsetParent
节点内偏移
的像素值
计算公式:
position的left值+margin
,第一个定位的父元素的左边缘
-
element.style.left
- 用户可以自己定义,是css样式
- 返回的是字符串,包含单位
- 可读可写
-
clientLeft
左边border的宽度+左边滚动的宽度(如果存在,针对块级元素)
<div id="test">
a<br>a<br>a<br>a<br>a<br>a<br>a<br>a
</div>
#test {
overflow: auto;
position: absolute;
left: 80px; /* + */
margin-left: 10px; /* = 90px offsetLeft */
height: 100px;
width: 100px;
border: 8px solid red;
background: #f8f8f8;
}
var el = document.getElementById("test");
console.log( el.offsetLeft ); // (left + margin) 80 + 10 = 90
console.log( el.clientLeft ); // (border + left scrollbar) 8 + 0 = 8
上诉代码说明:元素的offsetLeft
的值,是等于元素的定位left
的值加上存在的margin
;
clientLeft/Top
clientLeft and clientTop only show the width of the border. No margin. No padding. No left/top position. Just border-width.
offsetLeft/Top
offsetLeft and offsetTop are the left/top specified values + the margin. No border. No padding.
offsettWidth/Hright
元素自身的宽度和高度,不包括因 overflow 而未显示的部分,也就是其实际占据的宽度,整型,单位像素
clientHeight/Width
内容可视区域的高度,也就是说页面浏览器中可以看到内容的这个区域的高度,一般是最后一个工具条以下到状态栏以上的这个区域,与页面内容无关。
网友评论