在 jQuery 中使用 'this' 属性使代码可重用



嗨,a创建了一个代码,当元素出现在视野中时添加一个类,如果你愿意,视差。 但是,我希望这些物品以不同的速度进入下一个比前一个慢。但是,我似乎无法使用"this"属性使此代码可重用,这样我就不必为我想使用它的每个实例重写它。

if (!jQuery('#thumbnail-section-1 #thumbnail-preview.thumbnail-preview-fade-in').hasClass("is-showing")) {    
      if(wScroll > $('#thumbnail-section-1').offset().top - ($(window).height() / 1.2)) {
        $('#thumbnail-section-1 #thumbnail-preview.thumbnail-preview-fade-in').each(function(i){
          setTimeout(function(){
            $('#thumbnail-preview.thumbnail-preview-fade-in').eq(i).addClass('is-showing');
          }, (700 * (Math.exp(i * 0.35))) - 700);
          setTimeout(function(){
            $('#thumbnail-section-1 .overlay2 h2').eq(i).addClass('showing');
          }, (700 * (Math.exp(i * 0.35))) - 700);
        });
      }
    }
实际上不需要

使用 this,因为您的.each调用也可以传递当前元素:

var $sect = $('#thumbnail-section-1');
var $sel = $sect.find('#thumbnail-preview.thumbnail-preview-fade-in');
var $h2 = $sect.find('.overlay2 h2');
if (!$sel.hasClass('is-showing')) {
    if (wScroll > $sect.offset().top - ($(window).height() / 1.2)) {
        $sel.each(function(i, el) {   // <-- here
            var delay = 700 * (Math.exp(i * 0.35) - 1);
            setTimeout(function() {
                $(el).addClass('is-showing');
                $h2.eq(i).addClass('showing');
            }, delay);
        });
    }
}

最新更新