【问题标题】:Use Waypoints to add the same class for multiple elements使用 Waypoints 为多个元素添加相同的类
【发布时间】:2021-10-05 15:10:53
【问题描述】:

当元素在视口中可见时,我想使用 jQuery Waypoints 向元素添加一个类。定位一个元素很简单,但我不知道如何将它与多个元素一起使用。应该是这样的:

$(function() {
    const MyVariable = [
        'main.home section.blocks .text', 
        'main.page ul li',
        'main.contact .header div',
        'etc etc',
    ];
    
    $(MyVariable).waypoint(function() {
        $(this.element).addClass('animate');
    }, { 
        offset: '100%'
    });
});

感谢您的帮助!

【问题讨论】:

    标签: jquery constants viewport jquery-waypoints waypoint


    【解决方案1】:

    您不必将选择器保存在数组中。 你可以这样做:

    $('.selector1,.selector2,.selector3').waypoint(function() { ...}
    

    或者按照你的方式进行(使用数组),但你需要使用 for 循环绕过它们:

    $(MyVariable).each(function(){
    var self = $(this);
     $(this).waypoint({
             handler: function(){
                 self.addClass('animate');
             }
        });
    })
    

    我不能 100% 确定,因为我没有测试过,但我希望它对你有用或给你指导。

    【讨论】:

    • 感谢您的帮助托多。是的,第一个选项有效,但我需要为很多元素添加 Waypoint 功能。因此,为了概述和正确的代码,我想将每个元素放在不同的规则上。我尝试了您的数组示例,但不幸的是它不起作用。还有其他想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    相关资源
    最近更新 更多