scroll滚动监听实现animate返回顶部(有坑)

就是常见网页里滚动到一定高度,出现返回顶部按钮,触发事件按钮再消失。animate巨坑。

html

<div class="J_goTop"><img src="../res/static/img/totop.png" alt=""></div>

js

<script>
$(document).scroll(function() {
    var scroH = $(document).scrollTop();  //滚动高度
    if (scroH >= 100) { // 显示
        $('.J_goTop').css("display", "block")  // $('.J_goTop').fadeIn();
    } else{ // 消失
        $('.J_goTop').removeAttr("style")  // $('.J_goTop').fadeOut();
    }
    // 点击事件 
    $('.J_goTop').click(function(){
      if(scroH!=0){// 判断好像无效 :)
        // 巨坑!!!执行animate前先结束这个循环动作
        $('body,html').stop().animate({}).animate({ // document,window对象不能执行animate
          scrollTop: '0px',
        }, 600);
        return false;
      }
    })
  });
</script>

css

/* 回到顶部 */
.J_goTop{
  position: fixed;
  bottom: 10%;
  right: 1%;
  cursor: pointer;
  width: 2.5rem;
  height: 2.5rem;
  display: none;
}
.J_goTop img{width: 100%;height: 100%}

ps:一直以为是样式未及时清除…然后发现是jq中animate动画第二次点击事件没反应。

原因:第一次触发后就一直在重复执行scroll=0的操作,导致无法进行第二次,也就是再次下拉会卡顿闪烁。

解决:执行animate前,先结束这个上一次动作,再执行操作。

$(‘body,html’).stop().animate({‘为空或具体操作’}).animate({
  scrollTop: ‘0px’,
}, 600);

借鉴:https://zhidao.baidu.com/question/542439686.html

猜你喜欢

转载自www.cnblogs.com/xiong88/p/12461052.html
今日推荐