- 获取元素的位置 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:
- 鼠标事件对象的位置
2.1 pageX、pageY:鼠标相对于整个文档的距离,会受滚动条的影响
2.2 clientX、clientY(别名x、y):鼠标相对于可视区域的距离,不受滚动条的影响
2.3 offsetX、offsetY:鼠标相对目标节点的左边、上边的距离
2.4 screenX、screenY:鼠标相对于整个屏幕的距离
点击白色小方块区域时:
当页面向下滚动一些距离,依旧点击白色小块区域:
-
页面滚动的距离:window.scrollX、window.scrollY
-
获取或设置滚动条到元素左边的距离: 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>