目的関数
- ボックスをクリックした後、徐々にトップに戻るのではなく、すぐに達します
コードの実装
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
height: 2000px;
}
header {
height: 100px;
background-color: skyblue;
}
div {
position: fixed;
top: 150px;
left: 50%;
width: 200px;
height: 200px;
transform: translateX(-50%);
background-color: tomato;
line-height: 200px;
text-align: center;
font-size: 20px;
color: #ffffff;
cursor: pointer;
}
</style>
</head>
<body>
<header>我是顶部</header>
<div>返回顶部</div>
<script>
var div = document.querySelector('div')
div.addEventListener('click', function () {
animate(window,0)
})
function animate(obj, target, callback) {
clearInterval(obj.timer)
obj.timer = setInterval(function () {
if (obj.pageYOffset == target) {
clearInterval(obj.timer)
callback && callback()
}
var step = (target - obj.pageYOffset) / 10
step = step < 0 ? Math.floor(step) : Math.ceil(step)
window.scroll(0,obj.pageYOffset + step )
}, 15)
}
</script>
</body>
</html>