JavaScript实现网页带动画返回顶部

1,444 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第16天,点击查看活动详情

服务器由阿里云换到了腾讯云,我的代码之前一直都是托管在git上的,但是搬家的时候,可能是着急了,之前有些新加的文件没有托管到git上,所以,就丢了。

不过无所谓了,可以重新写嘛。

之前博客的回到顶部功能是请之前的一位前端的同事帮忙写的,这次打算自己尝试一下。

返回顶部无非就是锚点。

第一个版本:

<body style="height:2000px;">
    <div id="topAnchor"></div>
    <a href="#topAnchor" style="position:fixed;right:0;bottom:0">回到顶部</a>
</body>

这个没用js,单纯的使用锚点试了一下,好用。

好用是好用,但是用户体验不是很好,嗖的一下就回到顶部了。不好。

我不太喜欢使用jquery,不管坐什么都喜欢用原生,所以,我这里用原生JavaScript写了一个带动画的,大概是这样。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>返回顶部</title>
    <style >
        * {
            margin: 0;
            padding: 0;
        }
        body {
            height: 2000px;
            width: 100%;
        }
        .to_top {
            width: 60px;
            height: 60px;
            bottom: 10%;
            right: 20px;
            font-size: 40px;
            line-height: 70px;
            border: none;
            background: rgba(0, 0, 0, 0.2);
            cursor: pointer;
            opacity: 0;
            transition: all 1s;
            /*使点前标签始终置于最上层*/
            position: fixed;
            z-index: 99999;
        }
    </style>
</head>

<body>
    <div  class="to_top">
        <img src="https://guanchao.site/assets/up.abc2d8e9.png" alt=""  width="70;">
         </div>
     
    <script >
        window.onscroll = function () 
        {
            var timer = null;//时间标识符
            var isTop = true;

            var obtn = document.getElementsByClassName('to_top')[0];
            obtn.onclick = function () {
                // 设置定时器
                timer = setInterval(function () 
                {
                    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
                    //减小的速度
                    var isSpeed = Math.floor(-osTop / 6);
                    document.documentElement.scrollTop = document.body.scrollTop = osTop + isSpeed;
                    //判断,然后清除定时器
                    if (osTop == 0) {
                        clearInterval(timer);
                    }
                    isTop = true;//添加在obtn.onclick事件的timer中 
                }, 30);
            };
            //获取页面的可视窗口高度
            var client_height = document.documentElement.clientHeight || document.body.clientHeight;

            //在滚动的时候增加判断,忘了的话很容易出错
            var osTop = document.documentElement.scrollTop || document.body.scrollTop;
            if (osTop >= client_height) 
            {
                obtn.style.opacity = '1';
            } 
            else 
            {
                obtn.style.opacity = '0';
            }
            if (!isTop) {
                clearInterval(timer);
            }
            isTop = false;
        }
    </script>
</body>

</html>

以上代码可以放到html文件中可以直接运行。

代码具体含义其中基本都有注释。

有看不懂的地方,请自行百度。

最后放一下在我博客中实际应用的效果:

1234.gif

有好的建议,请在下方输入你的评论。

欢迎访问个人博客 guanchao.site

欢迎访问我的小程序:打开微信->发现->小程序->搜索“时间里的”