JS和JQuery监听滚动条事件

网上查了一下,找到两种js监听滚轮事件的方法

(1)window.onscroll = function() {} 

(2)document.addEventListener("onscroll", function (e) {})

js例子:

<a id="scrollup" href="#top" style="position:fixed;z-index: 999;display: none;">^</a>
#scrollup{
        background: #777;
        color:#eee;
        font-size: 40px;
        text-align: center;
        text-decoration: none;
        bottom:65px;
        right:20px;
        overflow: hidden;
        width:46px;
        height:46px;
        border:none;
        opacity:.8;
        &:active{opacity:.7;}
    }
<script type="text/javascript">
         window.onscroll= function(){
                //变量t是滚动条滚动时,距离顶部的距离
                var t = document.documentElement.scrollTop||document.body.scrollTop;
                var scrollup = document.getElementById('scrollup');
                //当滚动到距离顶部200px时,返回顶部的锚点显示
                if(t>=200){
                    scrollup.style.display="block";
                }else{          //恢复正常
                    scrollup.style.display="none";
                }
            }
</script>

写成jquery的话就是比如这样:

猜你喜欢

转载自blog.csdn.net/Cai181191/article/details/82799258