原生js写的回到顶部特效

css代码:

<style>
.top{
width:50px;
height: 50px;
border-radius: 5px;
background-color: #46e8ee;
font-size: 40px;
color: #ffffff;
line-height: 50px;
text-align: center;
cursor: pointer;
display: none;
position: fixed;
right: 15px;
bottom: 15px;
}
</style>

html代码:

<div class="top" id="top">^</div>

js代码:

<script>
topobj=document.getElementById('top');
// 当窗口发生滚动时候边滚动边计算高度
window.onscroll=function(){
// 获取滚动的高
st=document.documentElement.scrollTop;
if(st>=1000){
topobj.style.display='block';
}else{
topobj.style.display='none';
}
}
topobj.onclick=function(){
// document.documentElement.scrollTop=0;
st=document.documentElement.scrollTop;
v=60; //速度
ftop=setInterval(function(){
// 滚动的高减去速度
st-=v;
if(st<=0){
st=0;
clearInterval(ftop);
}
document.documentElement.scrollTop=st;
},30)
}
</script>
posted on 2018-03-30 17:33  AFew  阅读(96)  评论(0编辑  收藏  举报