小码农养成记

前端实现滚动到顶部的三种方式

2021-10-08  本文已影响0人  F_wind

css, html, dom

image.png

创建测试页面

<body>
    <div id='v1' style='height:100vh;width:100px;background-color:red;'>
    </div>
    <div id='v2' style='height:100vh;width:100px;background-color:blue;'>
    </div>
</body>

锚点方式

使用页面的锚点链接进行滚动:

<head>
    <style>
         .t1 {
            margin-left: auto;
            width: 70px;
            height: 30px;
            background-color: deepskyblue;
            bottom: 10px;
            border-radius: 5px;
            position: sticky;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>
    <div class='t1' id='t1'><a href='#v1'>锚点</a></div>
</body>

直接滚动

使用 window 的 scrollTo 方法进行滚动:

<head>
    <style>
         .t2 {
            margin-left: auto;
            width: 70px;
            height: 30px;
            background-color: deepskyblue;
            bottom: 70px;
            border-radius: 5px;
            position: sticky;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>
    <div class='t2' id='t2'><a href='#v1'>直接滚动</a></div>
</body>
<script>
    var t2 = document.getElementById("t2")
    t2.addEventListener("click", function (e) {
        normalScrollTo();
    })

    // 直接滚动
    function normalScrollTo() {
        window.scrollTo(0, 0);
    }
</script>

动画滚动

使用 window 的 scrollTo 方法,配合定时器实现动画滚动:

<head>
    <style>
         .t3 {
            margin-left: auto;
            width: 70px;
            height: 30px;
            background-color: deepskyblue;
            bottom: 130px;
            border-radius: 5px;
            position: sticky;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    </style>
</head>
<body>
    <div class='t3' id='t3'><a href='#v1'>动画滚动</a></div>
</body>
<script>
    var t3 = document.getElementById("t3")
    t3.addEventListener("click", function (e) {
        const {
            scrollY
        } = window;
        animationScrollTo(scrollY)
    })

    // 动画滚动
    function animationScrollTo(num) {
        const frequency = 5;
        if (num > 0) {
            setTimeout(function () {
                window.scrollTo(0, num);
                num = num - frequency;
                animationScrollTo(num);
            }, frequency);
        }
    }
</script>

整体效果

demo.gif
上一篇下一篇

猜你喜欢

热点阅读