JS小demo
要求:点击按钮之后又快到慢回到顶部,处于顶部位置时按钮消失
我才用的是比较笨的方法,思路是滚动条离顶端的距离越长,速度越快,反之显而易见,那么我便定义一个常量作为基底,随着scrolltop在滚动时越来越短,用scrolltop值除以这个常量,则就达到越来越慢。
<!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>Document</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
body{
height:2000px;
scroll-behavior: smooth;
background-image: linear-gradient( white,darkturquoise);
}
#header{
width: 100%;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
h1{
display: block;
height: 100px;
width: 100%;
font-size: 50px;
color: aqua;
font-weight: 700;
text-align: center;
}
#nav{
display:none;
height: 50px;
width: 50px;
background: url(./向上箭头粗小.png) no-repeat;
background-size: cover;
background-color: darkturquoise;
position: fixed;
bottom: 100px;
right: 20px;
}
</style>
<body>
<div id="header">
<h1 id="top">网页开头</h1>
</div>
<div id="nav"></div>
<script>
var nav=document.getElementById("nav");
const num=2;//定义的常量
window.onscroll=function(){
var t=document.documentElement.scrollTop;
console.log(t);
if(t==0){
nav.style.display="none";//当到达顶端时返回按钮消失。
}else{
nav.style.display="block";
}
}
nav.addEventListener("click",function(){
var time = setInterval(()=>{
var oheight=document.documentElement.scrollTop;
let speed=oheight/num;
document.documentElement.scrollTop-=speed;
console.log(speed);
//num++;
if(document.documentElement.scrollTop==0){
clearInterval(time);
}
},80)//数值越大越明显看到趋势,但是实用性不强。
})
</script>
</body>
</html>
页面样子:(右下角是返回按钮)
实现效果数据化