我有这个代码在滚动到视图时淡入div,但是当整个div在视口中时它只会淡化div。
当div的中间进入视口时,有没有办法让它运行淡入淡出?
<script>
$(document).ready(function() {
/* Every time the window is scrolled ... */
$(window).scroll( function(){
/* Check the location of each desired element */
$('.hideme').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* If the object is completely visible in the window, fade it it */
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},500);
}
});
});
});
</script>
答案 0 :(得分:2)
您的当前代码存在一些错误。
请检查位置与offset
之间的区别// middle of object and current viewport
var
middle = $(this).offset().top + ($(this).outerHeight() / 2),
top = $(window).scrollTop(),
bottom = top + $(window).height()
;
尝试直接使用滚动窗口事件:
// @see http://ejohn.org/blog/learning-from-twitter/
var scrollHappened = false;
$(window).scroll(function() {
scrollHappened = true;
});
setInterval(function() {
if (scrollHappened) {
scrollHappened = false;
checkLazyLoading();
}
});
此外,删除您已加载的元素以限制在页面上检查的元素数量
$(this)
// remove class, since we're already loading this element
.removeClass('lazyload')
// animate to visibile
.animate({'opacity':'1'}, 500)
;
检查以下jsFiddle,它在页面上有两个隐藏元素,当它们应该是半可见时动画显示为visibile。
答案 1 :(得分:0)
我认为只需加上div的一半高度就可以了:
var bottom_of_object = $(this).position().top + ( $(this).outerHeight() / 2 );
获得div的中间而不是底部。您可能希望重命名变量。