动画函数
function animate(obj, target, callback) {
clearInterval(obj.timer)
obj.timer = setInterval(function() {
var step = (target - window.pageYOffset) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (window.pageYOffset == target) {
clearInterval(obj.timer);
if (callback) {
callback();
}
}
window.scroll(0, window.pageYOffset + step);
}, 15);
}
HTML页面
<!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>
<script src="./static/js/updownanim.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div class="tab">点击回到顶部</div>
<style>
div {
width: 700px;
height: 400px;
background-color: #ccc;
margin: 0 auto;
}
div:nth-child(odd) {
background-color: greenyellow;
}
.tab {
width: 50px;
height: 300px;
background-color: pink;
position: fixed;
bottom: 100px;
right: 0;
}
</style>
<script>
var tab = document.querySelector('.tab')
tab.addEventListener('click', function() {
animate(window, 0)
})
</script>
</body>
</html>