JS练习_返回顶部_防抖实现

预览:

源码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>防抖与节流</title>
    <style>
        body{
            height: 2000px;
        }
        button{
            position:fixed;
            right: 100px;
            bottom: 100px;
            display: none;
        }
    </style>
</head>
<body>
<h1>window.onscroll事件</h1>
<button>回到顶部</button>
<script>

返回顶部效果
1、window.onscoll事件:滚动条滚动事件
2、document.documentElement.scrollTop:页面滚动位置距离顶部距离
3、window.scrollTo(0,0):让页面滚动条返回至顶部
*/

        let btn = document.querySelector("button")
        btn.onclick = function (){
            window.scrollTo(0,0);
        }
        let timer = null;
/*

        window.onscroll = function (){
            // 防抖开始
            if (timer!== null){
                clearTimeout(timer);
            }
            timer = setTimeout(()=>{
                console.log("Hello world!");
                if (document.documentElement.scrollTop > 0){
                    btn.style.display = "block";
                }else {
                    btn.style.display = "none";
                };
                timer = null;
            },500)

        }
*/

</script>

</body>
</html>
posted @ 2021-09-23 18:24  博客zhu虎康  阅读(67)  评论(0编辑  收藏  举报