繁体   English   中英

jQuery循环了“添加类”方法,但延迟了

[英]jQuery loop an “add class” method with a delay between

我现在正在创建一个站点,其中包括几部分,其元素以“层叠”样式显示(一个接一个,另一个之间有延迟)。 这是我的方法:

setTimeout(function(){
         $('nav .icon-hola').toggleClass('colorHigh');      },300);     
      setTimeout(function(){
         $('nav .icon-progra').toggleClass('colorHigh');      },400);          
      setTimeout(function(){
         $('nav .icon-sistemas').toggleClass('colorHigh');      },500);       
      setTimeout(function(){
         $('nav .icon-equipo').toggleClass('colorHigh');       },600);   
            setTimeout(function(){
         $('nav .icon-clases').toggleClass('colorHigh');      },700); 
      setTimeout(function(){
         $('nav .icon-social').toggleClass('colorHigh');      },800);       
      setTimeout(function(){
         $('nav .icon-contacto').toggleClass('colorHigh');       },900);   

有没有办法创建某种循环,在这种情况下,每100毫秒为每个$('nav [class^=icon-]') .addClass('colorHigh') $('nav [class^=icon-]')一个.addClass('colorHigh')方法?

如果有的话,以我正在做的方式或通过其他方式进行操作是否更可靠? 两者都需要相同的资源,或者其中之一需要更多的负载才能应用?

这将完成工作:

编辑代码

var delay=100;
$('nav [class^=icon-]').each(function(counter){
    //counter will start from 0..
    timeout = delay * (counter + 1);
    var selector = $(this);
    setTimeout(function(){
         selector.toggleClass('colorHigh');
    }, timeout);
});

DEMO

肯定会为您节省一些代码,

http://jsbin.com/yujujucoviqi/1/edit

var delay = 300;
var targetSelectors = [
  'nav .icon-hola',
  'nav .icon-progra',
  'nav .icon-sistemas'
];
function showInDelay(targetSelectors, delay, incrementDelayBy){
  if(!incrementDelayBy){
    incrementDelayBy=100;
  }
  var elems = [];
  if($.type(targetSelectors)==="string"){
    elems = $(targetSelectors);
  }else{
    elems = $(targetSelectors.join());
  }
$(elems).each(function(index,selector){
  setTimeout(function(){console.log(selector);
         $(selector).toggleClass('colorHigh');      
  },delay+=incrementDelayBy);
});  

}

    /*call this for as many selectors eg nav bars you require*/
showInDelay(targetSelectors, delay);

/*or with a selector*/
//showInDelay("nav [class^=icon-]", delay);

这是您可以使用的递归方法:

function toggleTimed(els, time){
    var el = [].shift.call(els)
       ,fn = function () {
               $(el).toggleClass('colorHigh'); 
               if (els.length) {toggleTimed(els,time);}
             };
    if (el) { setTimeout(fn, time);}
}

用法可能类似于:

toggleTimed($('[class^=icon]'),400);

这是jsFiddle中的一个简单演示

暂无
暂无

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

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