美文网首页让前端飞Web前端之路
案例:判断与顶部距离,点击按钮动态返回顶部

案例:判断与顶部距离,点击按钮动态返回顶部

作者: Hello杨先生 | 来源:发表于2019-07-09 16:09 被阅读3次

css

<style>
        #top {
            width: 50px;
            height: 30px;
            line-height: 30px;
            border-radius: 5px;
            background: skyblue;
            color: white;
            position: fixed;
            bottom: 100px;
            right: 30px;
            padding: 0 20px;
            cursor: pointer;
            display: none;
        }
    </style>

body

<body>

    1<br>
    1<br>
    <!--  n个 1<br>  节约控件 删除了-->

    <div onclick="topUp()" id="top">
        回顶部
    </div>
    <script>
        (function () {
            var $ = function (id) {
                return document.getElementById(id);
            }
            window.$ = $;
        })()

        var t;
        window.onscroll = function () {

            var topUp = document.body.scrollTop || document.documentElement.scrollTop;

            if (topUp > 200) {
                // document.getElementById("top").style.display = "block";
                $("top").style.display = "block";
            } else {
                $("top").style.display = "none";
            }

        }

        function topUp() {
            t = setInterval(function () {
                var st = document.body.scrollTop || document.documentElement.scrollTop;
                var speed = Math.floor(-st / 5);
                document.body.scrollTop = document.documentElement.scrollTop = st + speed;

                if (st === 0) {
                    clearInterval(t);
                }
            }, 100)


            // document.body.scrollTop = 0;
            // document.documentElement.scrollTop = 0;
        }
    </script>

</body>
image.png

相关文章

网友评论

    本文标题:案例:判断与顶部距离,点击按钮动态返回顶部

    本文链接:https://www.haomeiwen.com/subject/hrzxkctx.html