简单实现返回顶(底)部效果

1.首先需要一个div容器

<div class="returnTop"  onclick=‘toScroll('top')’>返回顶部</div>

<style>

.returnTop{

  position: fixed;

  bottom: 50px;

  right: 0;

  width: 40px;

  line-height: 25px;

  text-align: center;

  visibility: hidden;

}

</style>
2.当滚动条滑动都一定的距离时显示容器,这时需要获取滚动条距离页面顶部的距离:

function  getScroll() {

  var scroll; 
  //浏览器兼容 
        if (window.pageYOffset) {  
        scroll = window.pageYOffset; }  
        else if (document.compatMode && document.compatMode != 'BackCompat')  
        { 
    scroll = document.documentElement.scrollTop;
   }  
        else if (document.body) { 
    scroll = document.body.scrollTop;
   }   
        return scroll; 

}

3.实现返回顶(底)部动画函数:

function toScroll(target) {
        window.timer ? clearInterval(window.timer): '';
        var scrollHeight = document.body.offsetHeight - document.documentElement.clientHeight;
        window.timer = setInterval(()=> {
        var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
        switch (target) {
            case 'top':
                window.scrollBy(0, -100);
                if (Math.ceil(scrolltop) <= 0) {
                    clearInterval(window.timer);
                    delete window.timer;
                };
                break;
            case 'bottom':
                window.scrollBy(0, 100);
                if (Math.ceil(scrolltop) >= scrollHeight) {
                    clearInterval(window.timer);
                    delete window.timer;
                };
                break;
                }
            }, 30)
    }
 
4.实现:
  window.onscroll = ()=>{
    var dom = document.querySelector('.returnTop');
    if(getScroll() > 1200)  dom.style.visiblity = 'visible'
    else  dom.style.visibility = 'hidden';
  }
 
 
posted @ 2020-09-22 13:46  墨知白  阅读(180)  评论(0编辑  收藏  举报