我正在使用来自here的代码,但我需要它来显示div,当顶部滚动到视图而不是底部时,我该如何实现? JS Fiddle
$(document).ready(function() {
$(window).scroll( function(){
$('.hide').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},500);
}
});
});
});
答案 0 :(得分:2)
简单修复。当你真正达到顶峰时,诀窍是.animate()
。现在,你正在使用
var bottom_of_object = $(this).position().top + $(this).outerHeight()
您不需要$(this).outerHeight()
,因为这会增加您需要按div
的高度滚动的y位置。只需删除它就可以了
var top_of_object = $(this).position().top
$(document).ready(function() {
$(window).scroll(function() {
$('.hide').each(function(i) {
var bottom_of_object = $(this).position().top
var bottom_of_window = $(window).scrollTop() + $(window).height()
if (bottom_of_window > bottom_of_object)
$(this).animate({ opacity: '1' }, 500)
})
})
})

#container { height: 2000px }
#container div { background-color: gray; margin: 20px; padding: 80px }
.hide { opacity: 0 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div>shown</div>
<div>shown</div>
<div>shown</div>
<div>shown</div>
<div>shown</div>
<div>shown</div>
<div class="hide">Fade In</div>
<div class="hide">Fade In</div>
<div class="hide">Fade In</div>
<div class="hide">Fade In</div>
<div class="hide">Fade In</div>
</div>
&#13;
fiddle(后代)