JS中的offset,client,scroll系列相关属性

offset系列相关属性

  • offsetParent
  • offsetLeft
  • offsetTop
  • offsetWidth
  • offsetHeight

offset指偏移量,offset系列属性都是相对于父级元素的,可动态获取元素位置。
offsetParent是一个对象,是当前元素的父级元素。如果父级元素没有css定位,则为body
如果父级元素有css定位(position为absolute/relative/fixed),则为最近的有定位的父级元素。

offsetleft指当前元素距离父级元素的左偏移量。
offsetLeft指当前元素距离父级元素的上偏移量。
offsetWidth指当前元素的宽度。包括自身 padding,border。
offsetHeight指当前元素的高度。包括自身 padding,border。
offset系列获得的数值是没有单位的,且为只读属性,不能赋值。
对比style.width获得的是带单位(px)的字符串,style.width是可读写属性,不包含padding和border。
用offset属性获取值,用style设置值。

1
div.style.left = "100px";

案例 计算鼠标在盒子内的坐标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<body>
<div class="box"></div>
<script>
// 我们在盒子内点击, 想要得到鼠标距离盒子左右的距离。
// 首先得到鼠标在页面中的坐标( e.pageX, e.pageY)
// 其次得到盒子在页面中的距离(box.offsetLeft, box.offsetTop)
// 用鼠标距离页面的坐标减去盒子在页面中的距离, 得到 鼠标在盒子内的坐标
const box = document.querySelector('.box');
box.addEventListener('mousemove', function(e) {
// console.log(e.pageX);
// console.log(e.pageY);
// console.log(box.offsetLeft);
const x = e.pageX - this.offsetLeft;
const y = e.pageY - this.offsetTop;
this.innerHTML = 'x坐标是' + x + ' y坐标是' + y;
})
</script>
</body>

client系列相关属性

  • clientLeft
  • clientTop
  • clientWidth
  • clientHeight

client指的是元素本身的可视内容,不包括边框和滚动条。
clientLeft指当前元素的左边框宽度。
clientTop指当前元素的上边框宽度。
clientWidth指当前元素的可视宽度,包括自身padding,不含边框。
clientHeight指当前元素的可视高度,包括自身padding,不含边框。
client系列获取的内容也不含单位。

clientWidth,clientHeightoffsetWidth,offsetHeight都是只读属性,区别:

clientWidth,clientHeight获取的宽高为padding + 内容区
offsetWidth,offsetHeight获取的宽高为padding + 内容区 + 边框

scroll系列相关属性

  • scrollLeft
  • scrollTop
  • scrollWidth
  • scrollHeight

当我们用鼠标滚轮,滚动网页的时候,会触发 window.onscroll() 方法。
scrollLeft获取水平滚动条滚动的距离。
scrollTop获取垂直滚动条滚动的距离。
scrollWidth指当前滚动元素的实际宽度,包括 padding,不含 border。
scrollHeight指当前滚动元素实际高度,包括 padding,不含 border。

当某个元素满足scrollHeight - scrollTop == clientHeight时,说明垂直滚动条滚动到底了。
当某个元素满足scrollWidth - scrollLeft == clientWidth时,说明水平滚动条滚动到底了。

相关联

  • window.onscroll 屏幕滚动
  • window.onresize 屏幕窗口尺寸改变
  • window.onload 页面加载完毕
    屏幕分辨率:
1
2
window.screen.width
window.screen.height
1
2
3
window.onresize = function () {
document.title = window.screen.width + " " + window.screen.height;
}


JS中的offset,client,scroll系列相关属性
https://yueyc.top/2025/03/05/learnJS2/
作者
yueyc
发布于
2025年3月5日
许可协议