JavaScript实现回到顶部
#top{ display: none; position: fixed; left: 90%; bottom: 40px; height:60px; width: 60px; background: rgba(0,0,0,0.5); background-size:100% auto; border-radius: 5px; text-align: center; } #top i{ border-width:14px 10px; border-color:transparent transparent #000 transparent; border-style: dashed dashed solid dashed; }
window.onload=function(){ oTop=document.getElementById('top'); var time1=null; var isTop=null; oTop.onclick=function(){ //设置定时器 time1=setInterval(function(){ var osTop = document.body.scrollTop||document.documentElement.scrollTop; //ceil向上取整,floor向下取整 var speed=Math.ceil(osTop/2); document.body.scrollTop=document.documentElement.scrollTop=osTop-speed; if(osTop<=0){ clearInterval(time1); } isTop=true; },100); } //页面滚动自动触发: window.onscroll = function(){ //获取页面可视区高度和滚动高度 var osTop = document.body.scrollTop||document.documentElement.scrollTop; //这两个获取滚动的方法可以兼容多种浏览器 var clientHeight = document.documentElement.clientHeight; //对回到顶部的隐藏和显示,在css中一开始可以设置为隐藏 if (osTop>clientHeight) { oTop.style.display = "block" } else{ oTop.style.display = "none" } if (!isTop) { clearInterval(time1); } isTop = false; } }
版权声明:本文由Web学习之路发布,如需转载请注明出处。