jQuery each内でsetTimeoutを動作させる方法 – Using SetTimeout and each with jQuery

この記事は年前に書かれました。不適当な記述を含む場合がありますので、参考程度に留めてください。

どうもこんにちは。Toshikuraです。今回のTipsは【jQuery each内でsetTimeoutを動作させる方法 – Using SetTimeout and each with jQuery】です。地味に便利なのでメモしておきます(きもいデモができたのが本当の所です)。

実装方法

実装方法は至ってシンプルです。下の例ではクラス名【A】をeachでまわし、キーを使ってsetTimeoutで遅延を発生させています。

JS
$(function(){
$(‘.A’).each(function(k,v){
var $this = $(this)
setTimeout(function(){
$this.addClass(‘active’);
},100*k);
});
});
HTML
<span class="A"></span>
<span class="A"></span>
<span class="A"></span>
….
<span class="A"></span>
<span class="A"></span>
<span class="A"></span>

きもいデモ

ためしにクリックを基点として、その兄弟の子要素のクラスを着け外し(トグル)していきます。デモではクラスにcss3アニメーションを指定し、順次アニメーションするようにしています。きもいデモの意味はCLICKを連打するとわかります(chrome推奨)。

JS
$(function(){
$(‘.tab’).click(function(){
$(this).next(‘.list’).children().each(function(k,v){
var $this = $(this)
setTimeout(function(){
$this.toggleClass(‘active’);
},50*k);
});
});
});
HTML
<a class="tab" >CLICK</a>
<ul class="list">
<li><a href="">Afghanistan</a></li>
<li><a href="">Algeria</a></li>
<li><a href="">Andorra</a></li>
….
<li><a href="">Fiji</a></li>
<li><a href="">Finland</a></li>
<li><a href="">France</a></li>
</ul>
CSS
/* 装飾用(なくてOKです) */
.tabBd{width: 300px; margin: 0 auto;}
.tabBd *{user-select: none;-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;}
.tab{display: block; height: 40px; line-height: 40px; width: 300px; text-align: center; font-family: ‘Homenaje’, sans-serif; background: #19283D; color: #f6f6f6; }
.list li a{color: #f6f6f6; display: block; opacity: 0; background: #19283D; width: 300px; text-align: center; font-family: ‘Homenaje’, sans-serif; }

/* アニメーション用 */
.list{
width: 300px;
-moz-perspective:200; -webkit-perspective:200; -o-perspective:200; -ms-perspective:200;
-webkit-transform-origin: center bottom;
transform-origin: center bottom;
}

.list li {-webkit-transition:all 0.1s; transition:all 0.1s; height: 0; }

.list li a{
-webkit-transition:all 0.2s;
transition:all 0.2s;
-webkit-transform: rotateX(-120deg); transform: rotateX(-120deg);
-webkit-transform-origin: center top;
transform-origin: center top;
}

.list li.active{height: 40px;}
.list li.active a{-webkit-transform: rotateX(0deg); transform: rotateX(0deg); opacity: 1; height: 40px; line-height: 40px; }

以上になります。