前言
在使用JS操作DOM时,offsetTop、clientTop、scrollTop等属性是不是让你抓狂。本文总结了这些属性的用法
client系列
clientWidth
、clientHeight
都是只读属性
- clientWidth = 内容 + 左右padding
- clientHeigh = 内容 + 上下padding
clientTop
、clientLeft
都是只读属性
- clientTop = boder.top(上边框的宽度)
- clientLeft = boder.left(左边框的宽度)
clientX
、clientY
鼠标事件的属性,只读
- clientX: 相对文档的水平坐标
- clientY: 相对文档的垂直坐标
offset系列
offsetWidth
、offsetHeight
都是只读属性
- offsetWidth = width + 左右padding + 左右boder
- offsetHeight = height + 上下padding + 上下boder
offsetTop
、offsetLeft
都是只读属性。要了解这两个属性首先需要知道offsetParent
这个属性:
offsetParent
属性返回一个指向最近的(指包含层级上的最近)包含该元素的定位元素(relative,absolute,fixed)或者最近的table
,td
,th
,body
元素。当元素的style.display
设置为 "none" 时,offsetParent
返回null
。
- offsetTop:元素到offsetParent顶部的距离
- offsetLeft:元素到offsetParent左边的距离
总结:
对块级元素来说,offsetTop
、offsetLeft
、offsetWidth
及 offsetHeight
描述了元素相对于 offsetParent
的边界框。
offsetX
、offsetY
鼠标事件的属性
- event.offsetX 相对容器的水平坐标
- event.offsetY 相对容器的垂直坐标
scroll系列
scrollWidth
、scrollHeight
都是只读属性
scrollWidth:获取指定标签内容层的真实宽度(可视区域宽度+被隐藏区域宽度) scrollHeight:获取指定标签内容层的真实高度(可视区域高度+被隐藏区域高度)
scrollTop
、scrollLeft
可以设置或读取
scrollTop: 内容层顶部 到 可视区域顶部的距离
scrollLeft: 内容层左端 到 可视区域左端的距离