1. 程式人生 > >js和jquery監聽滾動條事件

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的話就是比如這樣: