Getting to combat web front end: HTML DOM event (to achieve a simple function back to top)

Javascript HTML DOM event allows different registered event handlers in an HTML document element. Event is usually used in conjunction with the function, the function will not be executed before the event occurs! (Such as the user clicks the button).

Getting to combat web front end: HTML DOM event (to achieve a simple function back to top)

Onscroll use the event to write a return to the top of the function code is as follows:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
        *{margin: 0;padding: 0;}
            #mybtn{position: fixed;height: 40px;width: 100px;background: red;border: none;border-radius: 5px;right: 20px;bottom: 20px;cursor: pointer;display: none;}
            #mybtn:hover{background-color: #888888;color: #FFFFFF;}    
    </style>
</head>
<body>
    <button id="mybtn" onclick="topfunction()" title="返回顶部">返回顶部</button>
    <div style="height: 100px;background-color: #000000;color: #FFFFFF;font-size: 50px;text-align: center;line-height: 100px;">向下滑动</div>
    <div style="background-color: lightgray;padding: 30px  30px 2500px;text-align: center;font-size: 30px;">实现返回顶部功能</div>
</body>
    <script>
        //浏览器窗口执行
        window.onscroll = function(){
            changeScroll();
        }
        //改变滚动距离 
        function changeScroll(){
            if(document.body.scrollTop >20 || document.documentElement.scrollTop >20){
                document.getElementById("mybtn").style.display = "block";
            }else{
                document.getElementById("mybtn").style.display = "none";
            }
        }
        function topfunction(){
            var timer = setInterval(function(){
                document.body.scrollTop -= 20;
                document.documentElement.scrollTop -=20;
                if(document.body.scrollTop ==0 && document.documentElement.scrollTop ==0){
                    clearInterval(timer);
                }
            },30)
        }
    </script>
</html>

web前端开发学习Q-q-u-n: 784-783-012 ,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习方法
(详细的前端项目实战教学视频,PDF)

Results are as follows:

Getting to combat web front end: HTML DOM event (to achieve a simple function back to top)

Guess you like

Origin blog.51cto.com/14592820/2449232