问题描述
适用范围:所有前端界面,返回顶部按钮
兼容:ie 9 以上
以下是实现功能的代码:
<div style="position: fixed; width: 40px; height: 40px; background: rgb(0, 0, 0); cursor: pointer; bottom: 202px; right: 100px; border-radius: 10px; display: none;" id="goup-container">
<div class="goup-arrow" style="width: 0px; height: 0px; margin: 0px auto; padding-top: 13px; border-style: solid; border-width: 0px 10px 10px; border-color: transparent transparent rgb(255, 255, 255);"></div>
</div>
<script>
//回到顶部按钮
window.onload = function() {
var top_btn = document.getElementById('goup-container');
var timer = null;
var isTop = true;
//获取页面的可视窗口高度
var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
//滚动条滚动时触发
window.onscroll = function(){
//在滚动的时候增加判断
var osTop = document.documentElement.scrollTop || document.body.scrollTop;//特别注意这句,忘了的话很容易出错
if (osTop >= clientHeight*0.15) {
top_btn.style.display = 'block';
}else{
top_btn.style.display = 'none';
}
if (!isTop) {
clearInterval(timer);
}
isTop = false;
};
top_btn.onclick = function(){
//设置定时器
timer = setInterval(function(){
//获取滚动条距离顶部的高度
var osTop = document.documentElement.scrollTop || document.body.scrollTop; //同时兼容了ie和Chrome浏览器
//减小的速度
var isSpeed = Math.floor(-osTop / 6);
document.documentElement.scrollTop = document.body.scrollTop = osTop + isSpeed;
//console.log( osTop + isSpeed);
isTop = true;
//判断,然后清除定时器
if (osTop == 0) {
clearInterval(timer);
}
},30);
};
}
</script>