我有以下代码:
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/