一键跳回顶部的功能很常见
但是又不想效果平平
不能一瞬间就跳回去
过程要平滑,固定步长会让过程平滑很多
代码:
<!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>
.long {
height: 2000px;
background-image: linear-gradient(#e66465, #9198e5);
}
#btn {
border: 1px solid black;
border-radius: 50%;
position: fixed;
right: 0;
bottom: 0;
height: 100px;
width: 100px;
display: none;
}
</style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div class="long"></div>
<button id="btn">to top</button>
</body>
<script>
$(function () {
$(document).scroll(function () {
// 返回顶部按钮的显示与隐藏
var scroH = $(this).scrollTop();
if (scroH > 0) {
$('#btn').show()
} else {
$('#btn').hide()
}
})
$('#btn').click(function () {
var scrollTop = $(document).scrollTop();
// 步长
var stepLong = 10;
// 每跳一步的间隔时间
var stepTime = 20;
console.log('滚动条的位置:', scrollTop)
var set = setInterval(function () {
// 滚动条距离顶部距离小于步长时,直接一步到位,不再执行按规定步长跳
if (scrollTop < stepLong) {
clearInterval(set)
window.scrollTo({
top: 0,
behavior: "smooth"
})
console.log('直接回到顶部')
} else {
// 设置固定的步长,让过程更顺滑
scrollTop -= stepLong
window.scrollTo({
top: scrollTop,
behavior: "smooth"
})
console.log('滚动条距离顶部距离:', scrollTop)
}
}, stepTime)
})
})
</script>
</html>
来源:CSDN
作者:卷尾巴
链接:https://blog.csdn.net/qq_41244810/article/details/104802664