<!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>
.box{
width: 500px;
height: 1500px;
border: 1px solid paleturquoise;
background-color: antiquewhite;
}
</style>
</head>
<body>
<div class="box"></div>
<button>回到顶部</button>
</body>
</html>
<script>
let btn = document.querySelector('button');
const scrollTop = () => {
//获取滚动条高度
const height = document.documentElement.scrollTop || document.body.scrollTop;
if(height > 20){//自定义高度
//浏览器页面每一次重绘的时候调用
window.requestAnimationFrame(scrollTop);
//将内容滚动到指定坐标
window.scrollTo(0,height-height/8);
}
}
btn.addEventListener('click',scrollTop);
</script>
JS页面滚动到顶部
最新推荐文章于 2024-07-05 10:20:02 发布