点击置顶

应用场景:当页面在下滑时右下角会有一个返回顶部,一点击会返回顶部

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <style>
        body {
      
            height: 2000px;
        }
        
        button {
      
            width: 300px;
            height: 60px;
            font-size: 30px;
            position: fixed;
            right: 5px;
            bottom: 5px;
        }
    style>
head>

<body>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Est, maiores. Dolorum rem itaque natus, alias ratione voluptas quo placeat eaque perspiciatis laboriosam inventore. Nam eius atque esse. At, dolor aut!
    <button>返回顶部button>

    <script>
        function win(attr, value) {
      
            if (typeof value == 'undefined') {
      
                return document.documentElement[attr] || document.body[attr];
            }
            document.documentElement[attr] = value;
            document.body[attr] = value;
        }
    script>

    <script>
        var body = document.querySelector('body');
        var btn = document.querySelector('button');

        btn.addEventListener('click', function() {
      
            var top = timer = null;
            timer = setInterval(function() {
      
                top = document.documentElement['scrollTop'];
                win("scrollTop", Math.floor(top - top / 30));
                if (top == 0) {
      
                    clearInterval(timer);
                }
            }, 10);
        })

        window.onload = window.onscroll = function() {
      
            var nowTop = win("scrollTop");
            btn.style.display = nowTop < 200 ? "none" : "block";
        }
    script>

body>

html>

点击置顶_第1张图片

你可能感兴趣的:(#,JavaScript小练习)