window事件-滚动事件(点击回顶部效果)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.main {
width: 1200px;
height: 2000px;
margin: 0 auto;
background-color: #ccc;
}
#gotop {
position: fixed;
right: 20px;
bottom: 50px;
width: 40px;
height: 40px;
text-align: center;
line-height: 40px;
color: #fff;
background-color: #999;
}
</style>
</head>
<body>
<div class="main"></div>
<div id="gotop">TOP</div>
</body>
<script>
var _gotop = document.getElementById("gotop");
var timer = null;
_gotop.onclick = function () {
clearInterval(timer);
timer = setInterval(() => {
document.documentElement.scrollTop -= 10;
var _st = document.documentElement.scrollTop || document.body.scrollTop;
console.log(_st);
if (_st === 0) {
clearInterval(timer);
}
}, 10);
}
// window.onscroll = function () {
// var st = document.documentElement.scrollTop || document.body.scrollTop;
// }
</script>
</html>