javascript - 当具有类的 div 进入 View 时触发函数 - 但不适用于具有该类的所有 div

标签 javascript jquery

当具有特定类的 div 靠近查看窗口顶部时,我花了很多时间尝试让动画正常工作。我有一些有效的东西,但它触发了类中 div 中的所有动画,而不仅仅是 View 中的动画。我认为 .each 会阻止这种情况发生?

$(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,所以如果您回答,请记住这一点。

最佳答案

这里的问题是这一行:

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

作为documentation表示,offset() 返回第一个匹配元素的偏移量,而不是全部。

请改用此代码:

$(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 ) {
    //...

关于javascript - 当具有类的 div 进入 View 时触发函数 - 但不适用于具有该类的所有 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876648/

相关文章:

javascript - 如何在 JavaScript 中停止函数多次执行?

javascript - 动态创建嵌套的 JSON 对象

javascript - JQuery 中动态添加的页面未使用新样式更新我的页面

jquery - 如何在 Internet Explorer 8 中正确对齐横幅

jquery - 如果是 FullCalendar 中的月 View ,则禁用拖放

javascript - 如何获取下拉列表的值

javascript - JQuery UI 可拖动多个恢复选项

javascript - 在 Javascript 中使用带引号的字符串内的变量?

javascript - Ajax函数进入循环

jquery - 滚动菜单中 jQuery stop() 中的奇怪效果/闪烁