我怎样才能让我的div用jquery淡出来

时间:2012-02-10 18:21:21

标签: jquery

当我从0.4滚动到1视图时,我正试图淡入div,这可以正常工作但是当用户滚过它时我不得不将其淡化为0.4。我怎么能这样做呢?

tiles = $("#project_images img").fadeTo(0, 0.4); // set the default image opacity to semi transparent

    $(window).scroll(function(d,h) {
        tiles.each(function(i) {
            a = $(this).offset().top + $(this).height();
            b = $(window).scrollTop() + $(window).height();
            if (a < b) $(this).fadeTo(1040,1); // when scrolling down over the image fade it IN.
            if (a > b) $(this).fadeTo(1040, 0.4); // when scrolling down over the image fade it OUT.
        });
    });

1 个答案:

答案 0 :(得分:1)

这是实现您的要求的一种方式。我从头开始考虑它,而不是调整您的逻辑。它归结为:

/**
 * on scroll, for each image do the following
 */

var visible    = /** is the image at all visible in the viewport? */ ;
var allVisible = /** is the image totally within the viewport? */ ;

if (visible) {
    if (allVisible) {
        $(this).stop().fadeTo(1040, 1);
    } else {
        $(this).stop().fadeTo(1040, 0.4);
    }
}

jQuery的stop()用于防止在图像上累积排队的fadeTo动画。我在演示中的代码牺牲了可读性的计算量,但随意刷卡并根据需要进行优化。