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

时间:2017-04-17 21:15:32

标签: javascript jquery html css css3

我有以下代码:

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

   }
});

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

现在我正在检查scrolledLengthdocumentHeight的对比。但是,问题似乎是documentHeight一旦我们到达底部就会发生变化,因为页脚会出现并扩展文档。

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

2 个答案:

答案 0 :(得分:1)

您已经在页脚中添加了一个类,可以使用CSS处理动画:

.footer {
  position: fixed;
  width: 100%;
  height: 100px;
  bottom: -100px;
  transition: all 200ms ease-out;
}

.footer.bottom {
  bottom: 0;
}

更新: JSFiddle with working slide up footer

显然我猜测页脚应该如何设置样式,因为你没有提供CSS - 这个代码只会在添加类.bottom时为页脚设置动画。

答案 1 :(得分:1)

尝试使用css转换:

&#13;
&#13;
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')
          

   }
});
&#13;
.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;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

    <div class="footer"></div>
    
</div>
&#13;
&#13;
&#13;