关于如何使用javascript监听滚动条滚动事件

在网页中,通常有一个通往网页顶部的锚点,现在我们就来实现它

Html代码:

<a id="scrollup" href="#top" style="position:fixed;z-index: 999;display: none;">^</a>

Css代码:

#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;
}

以上就是箭头所指按钮的样式啦,接下是实现滚动条监听事件~

javascript代码:

<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>

 

posted @ 2018-01-11 16:51  岁月淡忘了谁  阅读(673)  评论(0编辑  收藏  举报