問題 × 解決策

jQueryのstop()の設定を用いて、要素の挙動を制御する

問題

jQueryのアニメーションで、動作がずっと続いてしまう。

解決策

jQueryのstop()の設定を用いて、要素の挙動を制御する。

 

jQueryを用いたアニメーションの制御

jQueryを用いたアニメーションで、動作がずっと続くことのないよう、jQueryのstop()の設定を用いて、要素の挙動を制御する方法をご紹介します。

DEMOはこちら

クリックで開閉します。

現在のアニメーション:ストップ + 次のアニメーション:実行

stop(false, false)
内容が表示されます。

現在のアニメーション:ストップ + 次のアニメーション:ストップ

stop(true, false)
内容が表示されます。

現在のアニメーション:実行 + 次のアニメーション:実行

stop(false, true)
内容が表示されます。

現在のアニメーション:実行 + 次のアニメーション:ストップ

stop(true, true)
内容が表示されます。

HTML

HTMLはこちらになります。

<dl class="stops-list type01">
	<dt>stop(false, false)</dt>
	<dd>内容が表示されます。</dd>
</dl>
<dl class="stops-list type02">
	<dt>stop(true, false)</dt>
	<dd>内容が表示されます。</dd>
</dl>
<dl class="stops-list type03">
	<dt>stop(false, true)</dt>
	<dd>内容が表示されます。</dd>
</dl>
<dl class="stops-list type04">
	<dt>stop(true, true)</dt>
	<dd>内容が表示されます。</dd>
</dl>

CSS

CSSはこちらになります。

.stops-list > dt{
	padding: 5px 40px 5px 10px;
	color: #ffffff;
	font-weight: bold;
	background-color: #F15A24;
	position: relative;
	cursor: pointer;
}
.stops-list > dt:before{
	display: block;
	content: "";
	position: absolute;
	top:0; 
	right:10px;
	bottom:0;
	margin:auto;
	width: 20px;
	height: 2px;
	background-color: #ffffff;
	transition-duration: 0.2s;
	transform: rotate(90deg);
	-webkit-transform: rotate(90deg);
}
.stops-list > dt:after{
	display: block;
	content: "";
	position: absolute;
	top:0; 
	right:10px;
	bottom:0;
	margin:auto;
	width: 20px;
	height: 2px;
	background-color: #ffffff;
	transition-duration: 0.2s;
}
.stops-list > dt.on:before{
	transform: rotate(0deg);
	-webkit-transform: rotate(0deg);
}
.stops-list > dt.on:after{
	background-color: transparent;
}
.stops-list > dd{
	display: none;
	padding: 5px 10px;
	font-weight: bold;
}

Javascript

Javascriptはこちらになります。

$('.stops-list > dt').click( function() {
    $(this).toggleClass("on");
	if( $(this).closest('dl').hasClass('type01') ){
		$(this).next('dd').stop(false,false);
	}
	if( $(this).closest('dl').hasClass('type02') ){
		$(this).next('dd').stop(true,false);
	}
	if( $(this).closest('dl').hasClass('type03') ){
		$(this).next('dd').stop(false,true);
	}
	if( $(this).closest('dl').hasClass('type04') ){
		$(this).next('dd').stop(true,true);
	}
	$(this).next('dd').slideToggle(1000);
});

ポイント!

  • stop()」の各設定によって、現在のアニメーションと次のアニメーションを制御できます。
stop()の第1引数 stop()の第2引数 内容
false false 現在のアニメーションを途中でストップし、そこから次のアニメーションを実行する。
true false 現在のアニメーションを途中でストップし、さらに次のアニメーションもストップする。
false true 現在のアニメーションを最後まで実行し、そこから次のアニメーションも実行する。
true true 現在のアニメーションを最後まで実行し、そこから次のアニメーションをストップする。

参考ページ

以下のサイトが、より詳しく解説してくれています。

【【jQuery】stopメソッドを理解する – Qiita】
https://qiita.com/SotaSuzuki/items/92679f0135db3f0f85f6

コメント

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

sixteen + 9 =

「問題 × 解決策」
月別アーカイブ一覧

「問題 × 解決策」
月別アーカイブ一覧