当带有类的div进入视图时触发器功能 - 但不适用于具有该类的所有div

时间:2015-08-07 11:29:40

标签: javascript jquery

当特定类的div接近查看窗口的顶部时,我花了好几个小时试图让动画工作。我有一些有用的东西,但它会触发div中的所有动画,而不仅仅是视图中的动画。我想。还是会阻止这种情况发生吗?

$(function() {
    var animated = $('.js-animate'),
        distance = $(animated).offset().top,
        $window = $(window);
    replaceWithPaths(animated);
    hideSVGPaths(animated);

    $window.scroll(function() {

        $(animated).each(function(i) {

            if ( $window.scrollTop() >= distance-100 ) {
                startSVGAnimation(this);
                animated.splice(i,1);
            }
        });

    });
});

我尝试过使用插件(inview,waypoints),这两种插件都不符合要求。有简单的解决方案吗?你可能已经聚集在一起,我只是想要掌握JS / Jquery,所以如果你回答的话请记住这一点。

1 个答案:

答案 0 :(得分:1)

这里的问题是这一行:

distance = $(animated).offset().top

正如documentation所说,offset()返回第一个匹配元素的偏移量,而不是全部。{/ p>

请改用此代码:

$(function() {

    var animated = $('.js-animate'),
        distance = $(animated).offset().top,
        $window = $(window);

    replaceWithPaths(animated);
    hideSVGPaths(animated);

    $window.scroll(function() {

        $(animated).each(function(i) {

            //$(this).offset().top gives you the current offset of the current element.
            if ( $window.scrollTop() >= $(this).offset().top - 100 ) {
                startSVGAnimation(this);
                animated.splice(i,1);
            }
        });

    });
});

或者,如果你真的想保存偏移量,这样你就不必在滚动时反复访问该属性,你可以像这样保存它们:

//Saves the distances to an array.
distance = animated.map(function() {
    return $(this).offset().top;
}).get()

他们在each函数中访问它们,如下所示:

if ( $window.scrollTop() >= distance[i] - 100 ) {
    //...