js原生实现过渡效果的返回顶部功能实例

问题描述
适用范围:所有前端界面,返回顶部按钮
兼容: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>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

任聪聪

创作不易,你的打赏是我的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值