首页 > 其他 > 详细

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

时间:2020-03-11 11:42:06      阅读:65      评论:0      收藏:0      [点我收藏+]

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

html

<div class="J_goTop"><img src="../res/static/img/totop.png" ></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

 

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

原文:https://www.cnblogs.com/xiong88/p/12461052.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!