offsetParent,offsetLeft/Top
offsetParent
是最接近的祖先(ancestor),在浏览器渲染期间,它被用于计算坐标。
最近的祖先为下列之一
- CSS 定位的(position 为 absolute、relative、fixed 或 sticky)
<td>
、<th>
、<table>
元素<body>
元素
属性 offsetLeft
/offsetTop
提供相对于 offsetParent
左上角的 x/y 坐标。
例子
<main style="position: relative" id="main">
<article>
<div id="example" style="position: absolute; left: 180px; top: 180px">...</div>
</article>
</main>
<script>
alert(example.offsetParent.id); // main
alert(example.offsetLeft); // 180(注意:这是一个数字,不是字符串 "180px")
alert(example.offsetTop); // 180
</script>
有以下几种情况下,offsetParent 的值为 null:
- 元素的
display
属性为none
- 元素的
position
属性为fixed
- 元素的为
<html>
或<body>
元素
offsetWidth/Height (常用)
offsetWidth
和 offsetHeight
属性提供元素的尺寸(包括边框和内边距)。
对于未显示的元素,几何属性为 0/null
- 如果一个元素(或其任何祖先)具有 display:none 或不在文档中,则所有几何属性均为零(或 offsetParent 为 null)。
clientTop/Left
内侧与外侧的相对距离。 如果有滚动条,则 clientTop/Left 的值会增加。
clientWidth/Height
这些属性提供了元素边框内区域的大小。
它们包括了 “content width” 和 “padding
”,但不包括滚动条宽度(scrollbar):
总结
该属性获取元素内容区域和 padding
的大小,不包含滚动条。
如果 padding
为 0,则 clientWidth/Height
为内容区域的大小。
scrollWidth/Height
这些属性提供了元素的完整内容区域的大小,包括溢出部分。
scrollLeft/Top
这些属性提供了元素的滚动位置。 如果修改它们,则会滚动元素。