一、滚动事件
- 当页面进行滚动时触发的事件
- 事件名:scroll
- 监听整个页面滚动:
- 监听某个元素的内部滚动直接给某个元素加即可
window.addEventListener("scroll",function () {
console.log("我滚啦 你呢");
})
const div=document.querySelector("div");
div.addEventListener("scroll",function () {
console.log("div又开始滚啦");
})
1、获取滚动距离
window.addEventListener("scroll",function () {
console.log(document.documentElement.scrollTop);
})
2、主动设置滚动距离
const button = document.querySelector('button');
button.addEventListener('click', function () {
document.documentElement.scrollTop = 200;
});
3、滚动动画
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 200vh;
background-image: linear-gradient(black, red, blue, green);
}
a {
width: 150px;
height: 195px;
position: fixed;
bottom: 100px;
right: 50px;
background-image: url(./images/gotop.png);
}
a:hover {
background-image: url(./images/gotop.gif);
}
</style>
</head>
<body>
<a href="javascript:;"></a>
const a = document.querySelector('a');
window.addEventListener('scroll', function () {
const scrollTop = document.documentElement.scrollTop;
if (scrollTop > 700) {
a.style.display = 'block';
} else {
a.style.display = 'none';
}
});
a.addEventListener('click', function () {
let timeId = setInterval(function () {
document.documentElement.scrollTop -= 20;
console.log('定时器执行', document.documentElement.scrollTop);
if (document.documentElement.scrollTop === 0) {
clearInterval(timeId);
}
}, 10);
});