js实现点击回到顶部

24 篇文章 0 订阅

html部分

<div class="returnTop" id="btn">
        <i class="aui-iconfont aui-icon-top"></i>
 </div>

css部分

.returnTop {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    position: fixed;
    right: 0.75rem;
    bottom: 10%;
    background: #03a9f4;
    text-align: center;
    line-height: 60px;
}
.returnTop i {
    color: #fff;
    font-weight: bold;
    font-size: 1.5rem;
}
#btn{
	display:none;
}

js部分

// 返回顶部
        var obtn = document.getElementById('btn');
        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 == 0) {
                obtn.style.display = 'none';
            }else{
                obtn.style.display = 'block';
            }
            if (!isTop) {
                clearInterval(timer);
            }
            isTop = false;
        };
        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);  
        };
  • 8
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值