javascript - 用户滚动到页面底部后向上滑动页脚 - 闪烁

标签 javascript jquery html css

我有以下代码:

var footer = $('.footer'),
    extra = 0;

// footer.css({ opacity: '0', display: 'block' });


$(window).scroll(function() {

   var scrolledLength = ( $(window).height() + extra ) + $(window).scrollTop(),
       documentHeight = $(document).height();



    console.log( 'Scroll length: ' + scrolledLength + ' Document height: ' + documentHeight )


   if( scrolledLength >= documentHeight ) {

       footer
          .addClass('bottom')
          // .slideUp();
          .stop().animate({ bottom: '0', opacity: '1' }, 300);

   }
   else if ( scrolledLength <= documentHeight && footer.hasClass('bottom') ) {
        footer
           .removeClass('bottom')
          //  .slideDown();
           .stop().animate({ bottom: '-100', opacity: '0' }, 300);

   }
});

我的目标是在用户滚动到页面底部时显示页脚。如果用户再次向上滚动,我希望页脚再次向下滑动。

现在我正在根据 documentHeight 检查 scrolledLength。然而,问题似乎是当我们到达底部时 documentHeight 发生变化,因为页脚出现并且扩展了文档。

我的代码确实有效,页脚没有再次消失或其他任何东西,但它闪烁很多(然后最终平静下来),因为它正在重新计算。我怎么能解决这个问题?我的代码有错误吗?

最佳答案

尝试使用 css 过渡:

var footer = $('.footer'),
    extra = 0;

// footer.css({ opacity: '0', display: 'block' });


$(window).scroll(function() {

   var scrolledLength = ( $(window).height() + extra ) + $(window).scrollTop(),
       documentHeight = $(document).height();


   if( scrolledLength >= documentHeight ) {

       footer
          .addClass('open')
          
         

   }
   else if ( scrolledLength <= documentHeight && footer.hasClass('open') ) {
        footer
           .removeClass('open')
          

   }
});
.container{
  position:relative;
  height: 200vh;
  width:100%;
  background-color:red;
  overflow:hidden;
}

.footer{
  height: 100px;
  width:100%;
  position: absolute;
  left:0px;
  bottom:-100px;
  background-color: black;
  transition: 1s;
  
}

.open{
  bottom:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

    <div class="footer"></div>
    
</div>

关于javascript - 用户滚动到页面底部后向上滑动页脚 - 闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43459747/

相关文章:

javascript - 将无符号字节值转换为从 -1 到 1 的 float

jquery - 如何为元素设置动画同时更改其不透明度?

html - Bootstrap 4 Flexbox 将屏幕分成 4 部分

javascript - iframe 内容高度。使用父页面滚动 iframe 内容

php - 如何在多个网页上显示导航栏?

javascript - 从左侧拖动 div 效果不佳

javascript - 搜索数组并制作找到和未找到单词的编号列表,Javascript

javascript - HighChart 在 $.getJSON 之前创建

javascript - Jquery Accordion 上的图标更改

JqueryMobile Listview 删除旧值