2014-03-28 100 views
5

当我知道指定哪个元素时,我发现了这个问题的答案,但是我正在寻找的方法是检查'滚动'是否具有特定类的任何元素都已经进入视图,并按照它们的方式修改它们(例如,更改不透明度 - 只有那些进入视图的视图)。我知道代码可能看起来类似于此,但我无法使它工作:jQuery - 检查元素是否进入视图,淡入淡出

jQuery(window).on("scroll", function() { 
var difference = jQuery(window).offset().top + jQuery(window).height()/2; 
if (difference > jQuery(".makeVisible").offset().top) { 
    jQuery(this).animate({opacity: 1.0}, 500); 

} 
}); 

非常感谢。 注意:存在变量差异是因为我希望元素在到达屏幕中间时可见。

回答

4

Check if element is visible after scrollingUsing jQuery to center a DIV on the screen借款,以检查是否元素在屏幕的可视中心:

function isScrolledIntoView(elem) 
{ 
    var centerY = Math.max(0,((jQuery(window).height()-jQuery(elem).outerHeight())/2) 
        + jQuery(window).scrollTop()); 

    var elementTop = jQuery(elem).offset().top; 
    var elementBottom = elementTop + jQuery(elem).height(); 

    return elementTop <= centerY && elementBottom >= centerY; 
} 

我们可以然后修改您的方法:

jQuery(window).on("scroll resize", function() { 
    jQuery(".makeVisible").each(function(index, element) { 
     if (isScrolledIntoView(element)) { 
      jQuery(element).animate({opacity: 1.0}, 500); 
     } 
    }); 
}); 
+0

非常感谢,作品像魅力! – cVergel

0

我用skrollr.js插件来实现这一点,这是这里在github https://github.com/Prinzhorn/skrollr

然后你可以将参数以任何标签,因此,例如说你淡出图像,你可以有一个img像

<img src="img/blur/llhs_cake.png" alt="" height="115" width="118" class="overlay" id="llhs_cake" data--bottom-bottom="opacity:0;" data--top-top="opacity:0" data--top-top data--center-center="opacity=1"> 

标签与格式

data-[offset]-(viewport-anchor)-[element-anchor] 

所以它的使用 - 绕过偏移参数。

我想,这是实现你要找的,如果你再使用jQuery的东西附上像

$('*').attr("data--bottom-bottom="opacity:0;" data--top-top="opacity:0" data--top-center="opacity=1""); 

我在我的移动,所以我无法测试它的权利的最简单方法现在但我相信它应该有所帮助,如果不是,至少可以给你一个新的途径来尝试!

这些资源可以帮助您太: How to update (append to) an href in jquery?

Fade out element, when user reach the bottom of the screen