简体   繁体   English

如何将函数应用于类的所有元素

[英]How to apply function to all elements of a class

I have a function that I'd like to apply to several elements of the same class. 我有一个函数想要应用于同一类的多个元素。 It's a scroll page function and I need it to only execute once. 这是一个滚动页面功能,我只需要执行一次即可。 So I put it in a wrapper. 所以我把它放在包装纸里。 It works but I'd like to be able to just add a class to an element and have it act upon that element. 它可以工作,但是我希望能够将一个类添加到元素中,并使其作用于该元素。 I tried iterating through the elements and using addClass to add a unique class with their respective index added to the end but this did not work. 我尝试遍历元素,并使用addClass添加一个唯一的类,并将其各自的索引添加到末尾,但这没有用。 What I have now only acts upon the first element with the "split" class. 我现在所拥有的仅对具有“ split”类的第一个元素起作用。

//EXECUTES ONLY ONCE
function once(fn, context) { 
    var result;
    return function() { 
        if(fn) {
            result = fn.apply(context || this, arguments);
            fn = null;
        }
        return result;
    };
}
// Usage
//var split1 = once(function() {
//  fadeInText(".split1");
//});
const handlers = $(".split").toArray()
   .map(s => ({ el: $(s), show: once(() => fadeInText(s)) }));

$(window).scroll(function() {
    for(const {el, show} of handlers) {
    if( $(this).scrollTop() + $(window).height() > el.offset().top) 
       show();
  }
});

//SPLITTEXT
var f = ".split",
fadeInText(f);
function fadeInText(l) {
var el = document.querySelector(l);
var split = el.dataset.split;
var text = new SplitText(el, { type: split });
var tl = new TimelineMax({ paused: false });
var splitEls = text[split];
var wrapEls = function wrapEls(els) {
    return els.map(function (el) {
        return '<span style="display: inline-block">' + el.innerText + '</span>';
    });
};
var wrapped = wrapEls(splitEls);

splitEls.forEach(function (el, i) {
    el.style.overflow = 'hidden';
    el.innerHTML = wrapped[i];
});

var masks = splitEls.map(function (el) {
    return el.querySelector('span');
});

tl.staggerFrom(masks, 1.25, { skewY: 4, y: '200%', ease: Expo.easeOut, delay: 0.9 }, 0.1, 'in');
    return l;
}

$('.class').each(function(){ /* 'this' means the element */})

在函数内部, this可以被限制你在迭代的元素。

if you want a pure js application try this: 如果您想使用纯js应用程序,请尝试以下操作:

elements = document.querySelectorAll('.class');

elements.forEach((element, key) => {
        //your code
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM