scroll事件总结

一般监听窗口的滚动事件都是给window,document,body绑定滚动事件。但是需要注意以下几点:

(1)给body绑定scroll事件时,this指向window

(2)不管给谁绑定,要获取scrollTop值都是通过document.body来获取。即document.body.scrollTop.window和document是没有scrollTop值的。

给普通盒子设置scroll事件。

(1)此时需要一个条件,盒子必须有滚动条,可以理解为盒子的内容高度超过盒子本身。同时要给盒子设置overflow:scroll属性,这样盒子才能滚动。

(2)当滚动到尽头时,有这样一个关系式this.scrollTop + this.offsetHeight == this.scrollHeight。可以根据此关系式做很多事情,如判断盒子内容是否已完全展示出来了。

附上一段代码:可在控制台观察数值的变化

<style>
body{
/* height: 2000px; */
}
#father{
300px;
background-color: pink;
height: 300px;
overflow-y: scroll;
}
#son1{
height: 200px;
background-color: green;
}
#son2{
height: 200px;
background-color: skyblue;
}
#son3{
height: 200px;
background-color: #ccc;
}
</style>
</head>
<body>
<div id="father">
<div id="son1"></div>
<div id="son2"></div>
<div id="son3"></div>
</div>
<script>
var father = document.getElementById('father');
father.onscroll = function(){
console.log(this.scrollTop);
console.log(this.scrollHeight);
console.log(this.offsetHeight);
console.log(this.scrollTop + this.offsetHeight);
}
</script>
</body>

原文地址:https://www.cnblogs.com/justinwxt/p/6838433.html