【问题标题】:Show Div when scrolled to top edge not bottom edge滚动到顶部边缘而不是底部边缘时显示 Div
【发布时间】:2014-10-10 20:37:45
【问题描述】:
我正在使用来自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);
}
});
});
});
【问题讨论】:
标签:
javascript
jquery
css
【解决方案1】:
简单的修复。诀窍是当你真正达到顶峰时.animate()。现在,您正在使用
var bottom_of_object = $(this).position().top + $(this).outerHeight()
您不需要$(this).outerHeight(),因为这会将您需要滚动到的y 位置增加div 的高度。只需将其删除即可
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>
fiddle(留给后代)
【讨论】:
-
-
-
@Timothy 你想让 div 在窗口底部到达 div 之前淡入 40px 还是在窗口底部通过 div 顶部之后淡入 40px?本质上,这个picture——A 点还是 B 点?
-
@Timothy 然后使用var top_of_object = $(this).position().top + 40。这是fiddle。