画像を複数重ねて配置して、一定時間ごとに切り替える処理を実装する機会がたまにあるので、実装方法をメモ。
サンプルコード
切り替えのタイミングはJavaScript、切り替えの動きはCSSで対応します。
まずはHTMLを用意します。
<div class="switch-img js-switch-img"> <div class="switch-img_item is-current"> <img src="http://placehold.it/80x80/F0A202/&text=1"> </div> <div class="switch-img_item"> <img src="http://placehold.it/80x80/63768D/&text=2"> </div> <div class="switch-img_item"> <img src="http://placehold.it/80x80/D95D39/&text=3"> </div> </div>
.js-switch-imgでJavaScriptの設定、.switch-imgや.switch-img_itemでCSSの設定を行う想定です。
次にJavaScriptですが、DOM操作簡略化のためjQueryを使用します。
$(function() {
switch_img();
});
/**
* 一定時間ごとに画像を切り替える
* @param {number} time - 画像切り替えの待ち時間
*/
function switch_img(time) {
var target = $('.js-switch-img');
var current = 'is-current';
var wait = time || 3000;
setTimeout(function() {
for (var i = 0; i < target.length; i++) {
$wrapper = target.eq(i);
// 最後の画像以外は次の要素にカレントクラスを移動
if($wrapper.children('.' + current).index() < $wrapper.children().length - 1) {
$wrapper.children('.' + current).removeClass(current)
.next().addClass(current);
// 最後の画像の場合は先頭要素にカレントクラスを移動
} else {
$wrapper.children('.' + current).removeClass(current);
$wrapper.children().eq(0).addClass(current);
}
}
switch_img(wait);
}, wait);
}
switch_img()を実行することで画像切り替えを行えるようにしていて、引数で切り替えの待ち時間を設定できます。
.js-switch-imgの子要素に対してカレント用のclassをつけるようにしているので、構造を変更したり、切り替え用の要素以外を.js-switch-imgに入れないようにしてください。
最後にCSSです。
.switch-img {
position: relative;
width: 80px;
}
.switch-img_item {
/* 配置の設定 */
position: absolute;
top: 0;
left: 0;
width: 100%;
/* アニメーションの設定 */
opacity: 0;
transform: translateX(50px);
transition: 300ms;
}
.switch-img_item.is-current {
opacity: 1;
transform: translateX(0);
}
コメントに入れていますが、基本的に配置の設定は必須、その後のアニメーションの設定は必要に応じて変更してください。
これで一定時間ごとに画像を切り替えることができました。
一定時間ごとに画像を切り替えるデモページ
アニメーションの設定を変更することで切り替える動きを変更できます。
例えば回転して切り替わるようにしてみます。
.switch-img {
position: relative;
width: 80px;
}
.switch-img_item {
/* 配置の設定 */
position: absolute;
top: 0;
left: 0;
width: 100%;
/* アニメーションの設定 */
opacity: 0;
transform: rotateY(90deg);
transition:
opacity 100ms 200ms,
transform 300ms;
}
.switch-img_item.is-current {
opacity: 1;
transform: rotateY(0deg);
transition:
opacity 100ms 200ms,
transform 300ms 200ms;
}
コメントが承認されるまで時間がかかります。