JS的返回top操作
“返回顶部”实现是隐藏的,当滚动到一定高度时显示,点击后回到页面顶部top=0位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM</title>
<style>
body{height: 1000px;}
#Totop{
height: 20px;
border: 1px solid red;
display: none;
cursor: pointer;
position: fixed;
bottom: 100px;
right: 100px;
}
</style>
</head>
<body>
<span id="Totop"> ^ </span>
<script>
// Totop
let totop = document.getElementById('Totop');
totop.onclick = function (){ //返回到页面顶部
document.documentElement.scrollTop = document.body.scrollTop =0;
}
// 当页面滚动时触发
window.onscroll = function (){
if(getScrollY()>200){
totop.style.display='block';
}else{
totop.style.display='none';
}
}
// 得到页面向上滚动的距离
function getScrollY(){
return document.body.scrollTop || window.pageYOffset || window.scrollY;
}
</script>
</body>
</html>