文档事件——滚动事件
#6.23
描述:scroll事件会在【文档】或【元素】发生滚动操作时触发。
(1)文档滚动事件
说明:
属性scrollTop\scrollLeft表示文档滚动的距离:(没有单位)
语法:
IE:document.documentElement.scrollTop\Left
非IE:document.body.scrollTop\Left
兼容性:
(可以使用document.body.scrollTop||document.documentElement.scrollTop来解决兼容性)
举例:
//H5:<button>点我去1000的距离处</button>
document.querySelector('button').onclick=function(){
document.body.scrollTop=1000;
document.documentElement.scrollTop=1000;
}
//当文档滚动时事件自动发生
window.onscroll=function(){
//滚动事件调用一次,就输出一次滚动距离
console.log(document.body.scrollTop||document.documentElement.scrollTop);
}
案例:回到顶部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>案例:回到顶部</title>
<style>
body {
height: 2000px;
background: linear-gradient(yellowgreen, cornflowerblue); /*渐变*/
}
button {
position: fixed; /*固定定位*/
bottom: 20px;
right: 20px;
}
</style>
</head>
<body>
<button>回到顶部</button>
<script>
window.onscroll = function () {
console.log(document.documentElement.scrollTop);
}
var timer = null; //timer变量用于清空定时器
var button = document.querySelector('button');
button.onclick = function () {
//定时器:每个0.1s,向上移动100px
timer = setInterval(function () { //timer变量用于清空定时器
var top = document.documentElement.scrollTop || document.body.scrollTop;
top = top - 100;
console.log(top);
document.documentElement.scrollTop = top;
document.body.scrollTop = top;
if (top <= 0) clearInterval(timer); //<=而不是==为了防止不是整数0就一直不清空
}, 100)
// document.documentElement.scrollTop=0; //回到顶部
// document.body.scrollTop=0; //考虑兼容性
}
</script>
</body>
</html>
(2)元素滚动事件
元素发生滚动时并不存在兼容性的问题,但是需要有一个前提那就是:必须存在滚动条。
注:元素的滚动条属性可以使用overflow:scroll / overflow-x:scroll / overflow-y:scroll来实现
在元素发生滚动的时候,可以通过 元素.scrollTop/scrollLeft 获取到元素的位移距离。
。。。很少用。