关于距离的那些个值

博客介绍了JS中获取元素位置的方法,如offsetLeft、offsetTop与父元素position属性有关。还阐述了鼠标事件对象的位置,包括pageX、pageY等不同属性的含义及特点,同时提及页面滚动距离和元素滚动条距离的获取方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 获取元素的位置 offsetLeft 、offsetTop
    跟父元素的position属性(relative、absolute、fixed)有关;如果父级没有设置以上的值,则是相对于容器的距离;看下面的这个例子:
<style>
body {
  margin: 0px;
  height: 1300px;
}
.container {
  /* position: relative; */
  /* left: 200px; */
  margin-left: 200px;
  top: 20px;
  height: 300px;
  width: 300px;
  background-color: #eeee8a;
  border: 10px solid #fa8072;
}
.child {
  margin-left: 50px;
  width: 50px;
  height: 50px;
  background-color: #fff;
}
</style>
<body>
	<div class="container">
	    <div class="child"></div>
	</div>
</body>

此时 child 元素的父级没有设置position值,它的offsetLeft应该是相对于容器左边的:
在这里插入图片描述
此时我们修改下 container 的position:

container {
  position: relative;
  left: 200px; 
  top: 20px;
  height: 300px;
  width: 300px;
  background-color: #eeee8a;
  border: 10px solid #fa8072;
}

这时的 child 的 offsetLeft 应该是相对于 container的,应该是 50px:
在这里插入图片描述

  1. 鼠标事件对象的位置
    2.1 pageX、pageY:鼠标相对于整个文档的距离,会受滚动条的影响
    2.2 clientX、clientY(别名x、y):鼠标相对于可视区域的距离,不受滚动条的影响
    2.3 offsetX、offsetY:鼠标相对目标节点的左边、上边的距离
    2.4 screenX、screenY:鼠标相对于整个屏幕的距离

点击白色小方块区域时:
在这里插入图片描述
当页面向下滚动一些距离,依旧点击白色小块区域:
在这里插入图片描述

  1. 页面滚动的距离:window.scrollX、window.scrollY
    在这里插入图片描述

  2. 获取或设置滚动条到元素左边的距离: element.scrollLeft、element.scrollTop

<style>
#container {
    margin-left: 50px;
    margin-top: 50px;
    width: 200px;
    height: 200px;
    border: 1px solid #333;
    overflow-x: scroll;
}

#content {
    width: 450px;
    background-color: #dda0dd;
}
#slide {
	margin-left: 50px;
}
</style>
<body>
   <div id="container">
     <div id="content">Click the button to slide right!</div>
   </div>
   <button id="slide" type="button">Slide right</button>
</body>
<script>
button.onclick = function(e) {
   e.stopPropagation();
   // 获取或设置滚动条到元素左边的距离
   const container = document.getElementById('container');
   console.log('---element.scrollLeft, element.scrollTop', container.scrollLeft, container.scrollTop);
   // 滚动的宽度
   console.log('----scrollWidth, scrollHeight', container.scrollWidth, 	container.scrollHeight)
   container.scrollLeft += 20;
};
</script>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值