<!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>平滑返回顶部</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
position: relative;
height: 2000px;
background: linear-gradient(rgb(18, 219, 109), rgb(177, 57, 224))
}
button {
position: fixed;
right: 0;
bottom: 10px;
height: 80px;
background-color: cadetblue;
color: white;
font-size: 20px;
text-align: center;
line-height: 80px;
}
</style>
</head>
<body>
<button>返回顶部</button>
<script>
var btn = document.querySelector('button')
btn.onclick = function () {
//兼容
var x = document.documentElement.scrollTop || document.body.scrollTop
var time = setInterval(function () {
x = x - 10
if (x < 10) {
x = 0
window.scrollTo(x, x)
clearInterval(time)
}
window.scrollTo(x, x)
//慢-快 方法2
// window.scrollTo({
// top: 1000,
// behavior: "smooth"
// })
}, 5)
}
</script>
</body>
</html>
【返回顶部】
最新推荐文章于 2023-10-07 09:24:27 发布