当滚动到顶部时,我的所有对象同时具有可见性

时间:2014-05-19 16:21:52

标签: javascript jquery scroll opacity

我有不透明度0的对象(.hideme),当我们将它们滚动到屏幕时,它们变得可见。我使用jQuery:

$(document).ready(function() {

    $('.hideme').css({'opacity':'0'});

    /* 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 in */
            if(bottom_of_window > bottom_of_object){           
                $(this).stop(true).delay(800).animate({'opacity':'1'},600,'easeOutBack');     
            }           
        });   
    });

});

问题是,当我在屏幕上滚动第一个.hideme div时,所有其他.hideme div在同一时间获得不透明度1,但我想让它们只在屏幕上显示时可见! 你知道怎么做吗?提前谢谢。

您可以在此处查看:http://webdesign.igorlaszlo.com/demos.html

1 个答案:

答案 0 :(得分:1)

Dude,

首先:你最好使用css3过渡来使这个动画变得容易,因为如果你使用stop(),如果hideme应该是可见的并且用户继续滚动,你就会遇到麻烦。您可以创建一个类:

.hideme {
    opacity:0;
    transition:opacity 0.6s ease;
    -webkit-transition:opacity 0.6s ease;
    -moz-transition:opacity 0.6s ease;
    -o-transition:opacity 0.6s ease;
}

第二:你应该使用offset().top代替position().top。详细了解它们之间的区别。

这是我对你的建议:

http://jsfiddle.net/LEXgX/1/

您最好创建一个名为visibleHideme();的函数,并在$(document).ready()执行此函数。正如所有隐藏的' hideme'以opacity:0开头,如果有一些隐藏的'当页面加载时应该是可见的,用户不需要滚动页面使其可见。

    function visibleHideme(){
        $('.hideme').each(function(){

            var top_of_object = $(this).offset().top;
            var top_of_window = $(window).scrollTop();
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            if(top_of_object > top_of_window && bottom_of_window > bottom_of_object){
                $(this).css('opacity','1');
            }
            else {
                $(this).css('opacity','0');
            }

        });
    }
    visibleHideme();

然后,当用户滚动页面时,将执行相同的功能。

$(window).scroll(function(){
    visibleHideme();
});   
相关问题