【问题标题】:CSS3 & jQuery animate on scroll positionCSS3 & jQuery 在滚动位置上动画
【发布时间】:2013-09-13 13:15:07
【问题描述】:

我的代码有一些问题。我希望括号在用户滚动的屏幕上可见时进行动画处理。我的问题是页面上的所有 h2 元素同时动画,而不是在它们显示在屏幕上时。下面是使用的 jQuery,这里是一个 jsfiddle 的链接:

http://jsfiddle.net/CbxvH/18/

提前致谢, 迈克。

    $(window).scroll( function(){

        var test1 = $('article h2 span.bracket1');
        var bottom_of_object1 = $(test1).position().top + $(test1).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();

        if( bottom_of_window > bottom_of_object1 ){

            $(test1).addClass( "slideLeft" );
            setTimeout(function() {
              $("article h2 .spanContent").animate({'opacity':'1'},1000);
            }, 1000);


    };

        var test2 = $('article h2 span.bracket2');

        var bottom_of_object2 = $(test2).position().top + $(test2).outerHeight();

        if( bottom_of_window > bottom_of_object2 ){

            $(test2).addClass( "slideRight" );

        };

        var test3 = $('article h2 span.bracket3');

        var bottom_of_object3 = $(test3).position().top + $(test3).outerHeight();

        if( bottom_of_window > bottom_of_object3 ){

            $(test3).addClass( "slideLeft" );
            setTimeout(function() {
              $("article h2 .spanContent2").animate({'opacity':'1'},1000);
            }, 1000);

        }

        var test4 = $('article h2 span.bracket4');

        var bottom_of_object4 = $(test4).position().top + $(test4).outerHeight();

        if( bottom_of_window > bottom_of_object4 ){

            $(test4).addClass( "slideRight" );

        }


});

每条语句:

$('.featureImages img, article p, article ul li').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'},1000);

        }

    }); 

【问题讨论】:

    标签: javascript jquery css scroll jquery-animate


    【解决方案1】:

    您是否尝试过使用offset() 而不是position()

    var offset =  $(test1).offset();  
    var bottom_of_object1 = offset.top + $(test1).outerHeight();
    

    【讨论】:

    • 这似乎奏效了。我不明白为什么 position() 适用于我在文档中进一步提出的“每个”语句而不是这个。也许您可以对此有所了解?我已经编辑了代码以包含每个语句。
    • 我认为这与您分配给元素的position: absolute 有关。 position() 获取相对于父元素的坐标,offset()document 获取它们。
    猜你喜欢
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 2012-06-17
    相关资源
    最近更新 更多