jQuery循环"添加类"之间的延迟的方法

jQuery loop an "add class" method with a delay between

本文关键字:quot 方法 延迟 之间 添加 循环 jQuery      更新时间:2023-09-26

我现在正在创建一个包含几个部分的网站,这些部分的元素以"级联"样式出现(一个接一个,中间有延迟)。我是这样做的:

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')方法?

如果有的话,用我现在的方式做还是用另一种方式做更可靠?两者都需要相同的资源,还是其中一个需要更多的负载来应用?

这将完成工作:

<<p> 编辑代码/strong>
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);
});
演示

这当然会为你节省一些代码,

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
中有一个简单的演示
相关文章: