画像切り替え switcher スイッチャー html挿入式リンクボタン付き

画像切り替え機能の制作例

画像切り替え機能の制作例

画像切り替え switcher スイッチャー html挿入式リンクボタン付き

主な用途としてメイン画像用のスイッチャー/スワイパーです。JavaScriptコードを参考に自分好みに仕上げよう。

マウスやタッチによる左右スワイプでの画像切り替え可能。
右下のボタンによる画像切り替え、および、時間経過による画像自動切り替え。
レスポンシブ対応。
■ フローティングリンクボタンを設置可能な版です。
現時点のコードは以下の通り:
/**
 * 画像切り替え
 *
 * @author ao-system, Inc.
 * @date 2022-10-06
 * @date 2024-01-16
 * @date 2024-01-17 Rewrite the code using the class syntax.
 *

<section class="switchpanel">
	<div>
		<div id="switchPanelStage"></div>
	</div>
</section>

<style>
section.switchpanel {
	background-color: #000;
	> div {
		max-width: 1920px;
		margin: 0 auto;
		overflow: hidden;
		> #switchPanelStage {
			user-select: none;
			display: grid;
			grid-template-rows: 1fr;
			grid-template-columns: 1fr;
			> div {
				grid-row: 1/2;
				grid-column: 1/2;
				&:nth-of-type(1) {
					z-index: 0;
				}
				&:nth-of-type(2) {
					z-index: 1;
					transition: 0.5s;
					cursor: ew-resize;
				}
				&:nth-of-type(3) {
					z-index: 2;
					justify-self: flex-end;
					align-self: end;
					display: flex;
					justify-content: center;
					align-items: center;
					column-gap: 5px;
					padding: 0 20px 17px 0;
					@media (width < 670px) {
						column-gap: 3px;
						padding: 0 4px 4px 0;
						> span {
							> img {
								width: 16px;
							}
						}
					}
					> span {
						cursor: pointer;
						> img:nth-of-type(1) {
							display: block;
						}
						> img:nth-of-type(2) {
							display: none;
						}
						&.on {
							> img:nth-of-type(1) {
								display: none;
							}
							> img:nth-of-type(2) {
								display: block;
							}
						}
					}
				}
				//values
				> article {
					position: relative;
					> picture {
						> img {
							width: 100%;
						}
					}
					> a {
						text-decoration: none;
						position: absolute;
						&.button1 {
							left: 50px;
							top: 50px;
						}
						&.button2 {
							right: 80px;
							top: 100px;
						}
						&.button3 {
							left: 100px;
							bottom: 50px;
						}
						> img {
							max-width: 100%;
						}
					}
				}
			}
		}
	}
}
</style>
 *
 */

(() => {
	'use strict';
	class SwitchImage {
		#constProperties = [
			{prop: 'stage',					value: document.getElementById('switchPanelStage')},
			{prop: 'layer0',				value: document.createElement('div')},
			{prop: 'layer1',				value: document.createElement('div')},
			{prop: 'layerNav',				value: document.createElement('div')},
			{prop: 'markPause',				value: './image/panel_pause.svg'},
			{prop: 'markPlay',				value: './image/panel_play.svg'},
			{prop: 'markNavOn',				value: './image/panel_ball_on.svg'},
			{prop: 'markNavOff',			value: './image/panel_ball_off.svg'},
			{prop: 'buttonPause',			value: document.createElement('span')},
			{prop: 'buttonPlay',			value: document.createElement('span')},
			{prop: 'imageChangeInterval',	value: 4000},	//画像と画像の時間間隔
			{prop: 'slideWidth',			value: 50},		//切り替わるスライド幅
			{prop: 'slideTime',				value: 600},	//スライド時間cssの0.5sよりちょっと長め
			{prop: 'swipeShreshold',		value: 50},		//スワイプ判定幅
		];
		#loopTimeoutId			= null;		//自動動作のタイマー
		#isBusy					= false;	//動作中
		#pausePlayFlag			= true;		//falseで停止
		#focusFlag				= true;		//フォーカスが外れている時は動作させないため
		#valueIndex				= 0;		//this.#valuesの添え字
		#slideDirection			= 1;		//1|-1	正方向,逆方向
		#swipeStartX			= 0;		//スワイプ開始位置
		#isSwiping				= false;	//スワイプ中
		#values					= [];
		//
		constructor(values) {
			this.#values = values;
			this.#constProperties.forEach((obj) => Object.defineProperty(this, obj.prop, {value:obj.value, writable:false}));
			this.#init();
		}
		#init() {
			this.stage.appendChild(this.layer0);
			this.stage.appendChild(this.layer1);
			this.stage.appendChild(this.layerNav);
			//this.#values = shuffle(this.#values);	//シャッフルさせる場合
			//window.addEventListener('focus',() => { this.#focusFlag = true;});	//out focusで停止させる場合の処理
			//window.addEventListener('blur',() => { this.#focusFlag = false;});	//out focusで停止させる場合の処理
			//
			this.layer0.innerHTML = this.#values[0];
			this.layer1.innerHTML = this.#values[0];
			this.layer1.animate(
				[{opacity: 0}],
				{delay:0,duration:0, easing:'linear',fill:'forwards', },
			);
			this.#preload();
			this.#initNav();
			this.#initSwipe();
			this.#navOn();
			this.#autoSlide();
		}
		#shuffle(array) {
			for (let i = array.length - 1; i > 0; i--) {
				const j = Math.floor(Math.random() * (i + 1));
				[array[i], array[j]] = [array[j], array[i]];
			}
			return array;
		}
		//プリロード 最後に最初の表示になるように後ろから前へプリロードする
		#preload() {
			for (let i = this.#values.length - 1; i >= 0; i--) {
				setTimeout(() => {
					this.layer1.innerHTML = this.#values[i];
				},10);
			}
		}
		#initNav() {
			this.#values.map((x,index) => {
				const span = document.createElement('span');
				span.addEventListener('click',() => {
					if (this.#isBusy) {
						return;
					}
					this.#slideAction(index);
				});
				span.innerHTML = '<img src="' + this.markNavOff + '"><img src="' + this.markNavOn + '">';
				this.layerNav.appendChild(span);
			});
			const pauseImg = new Image();
			pauseImg.src = this.markPause;
			this.buttonPause.appendChild(pauseImg);
			this.layerNav.appendChild(this.buttonPause);
			const playImg = new Image();
			playImg.src = this.markPlay;
			this.buttonPlay.appendChild(playImg);
			this.layerNav.appendChild(this.buttonPlay);
			this.buttonPlay.style.display = 'none';
			this.buttonPause.addEventListener('click',() => this.#setPause());
			this.buttonPlay.addEventListener('click',() => this.#setPlay());
		}
		#initSwipe() {
			this.layer1.addEventListener('click', (e) => { e.preventDefault();});
			this.layer1.addEventListener('mousedown', (e) => { this.#swipeStart(e.clientX); });
			this.layer1.addEventListener('mouseup', (e) => { this.#swipeEnd(e.target, e.clientX); });
			this.layer1.addEventListener('touchstart', (e) => { this.#swipeStart(e.touches[0].clientX); });
			this.layer1.addEventListener('touchend', (e) => { this.#swipeEnd(e.target, e.changedTouches[0].clientX); });
		}
		#swipeStart(positionX) {
			if (this.#isBusy) {
				return;
			}
			this.#swipeStartX = positionX;
			this.layer1.style.cursor = 'grabbing';
			this.#isSwiping = true;
		}
		#swipeEnd(targetElm,positionX) {
			if (this.#isSwiping == false) {
				return;
			}
			if (this.#swipeStartX - positionX > this.swipeShreshold) {
				this.#slideAction(this.#withinRange(this.#valueIndex + 1));
			} else if (this.#swipeStartX - positionX < -this.swipeShreshold) {
				this.#slideDirection = -1;
				this.#slideAction(this.#withinRange(this.#valueIndex - 1));
			} else {
				let attrLink = null;
				let attrTarget = null;
				let targetElm2 = targetElm;
				for (let i = 0; i < 9; i++) {	//画像からこの回数の親を調べる
					targetElm2 = targetElm2.parentNode;
					if (targetElm2 == this.layer1) {
						break;	//リンクが無かった場合
					}
					attrLink = targetElm2.getAttribute('href');
					if (attrLink) {
						attrTarget = targetElm2.getAttribute('target');
						break;	//調査完了
					}
				}
				if (attrLink) {
					if (attrTarget) {
						window.open(attrLink, attrTarget);
					} else {
						window.location.href = attrLink;
					}
					return;
				}
			}
			this.layer1.style.cursor = '';
			this.#isSwiping = false;
		}
		#setPause() {
			this.#pausePlayFlag = false;
			this.buttonPause.style.display = 'none';
			this.buttonPlay.style.display = 'block';
		}
		#setPlay() {
			this.#pausePlayFlag = true;
			this.buttonPause.style.display = 'block';
			this.buttonPlay.style.display = 'none';
		}
		#slideForward() {
			if (this.#isBusy) {
				return;
			}
			this.#isBusy = true;
			this.#navOn();
			this.layer1.innerHTML = this.#values[this.#valueIndex];
			this.layer1.animate(
				[
					{opacity: 0,transform:'translateX(' + (this.slideWidth * this.#slideDirection) + 'px)'},
					{opacity: 1,transform:'translateX(0px)'},
				],
				{delay:0,duration:this.slideTime, easing:'ease-out',fill:'forwards', },
			);
			setTimeout(() => {
				this.layer0.innerHTML = this.#values[this.#valueIndex];
				this.layer1.animate(
					[{opacity: 0}],
					{delay:100,duration:0, easing:'linear',fill:'forwards', },
				);
				this.#slideDirection = 1;
				setTimeout(() => {
					this.#isBusy = false;
				},100);
			},this.slideTime);
		}
		#autoSlide() {
			this.#loopTimeoutId = setTimeout(() => {
				if (this.#pausePlayFlag && this.#focusFlag) {
					this.#slideAction();
				} else {
					this.#autoSlide();
				}
			}, this.imageChangeInterval - this.slideTime);
		}
		#slideAction(num = this.#valueIndex + 1) {
			clearTimeout(this.#loopTimeoutId);
			this.#valueIndex = this.#withinRange(num);
			this.#slideForward();
			this.#autoSlide();
		}
		#navOn() {
			const spans = this.layerNav.querySelectorAll('span');
			spans.forEach((elm) => elm.classList.remove('on'));
			spans[this.#valueIndex].classList.add('on');
		}
		#withinRange(nextNumber) {
			const num = (nextNumber >= 0) ? nextNumber : this.#values.length - 1;
			return num % this.#values.length;
		}
	}
	//
	new SwitchImage(
		[
			'<article><picture><source srcset="./image/panel01b.webp" media="(width < 700px)"><img src="./image/panel01.webp" draggable="false"></picture><a class="button1" href="https://ao-system.net/" target="_blank"><img src="./image/button1.svg"></a></article>',
			'<article><picture><source srcset="./image/panel02b.webp" media="(width < 700px)"><img src="./image/panel02.webp" draggable="false"></picture><a class="button2" href="https://www.aosystem.co.jp/" target="_blank"><img src="./image/button2.svg"></a></article>',
			'<article><picture><source srcset="./image/panel03b.webp" media="(width < 700px)"><img src="./image/panel03.webp" draggable="false"></picture><a class="button3" href="https://www.aosystem.co.jp/" target="_blank"><img src="./image/button2.svg"></a></article>',
			'<article><picture><source srcset="./image/panel04b.webp" media="(width < 700px)"><img src="./image/panel04.webp" draggable="false"></picture><a class="button1" href="https://www.google.com/" target="_blank"><img src="./image/button3.svg"></a></article>',
			'<article><picture><source srcset="./image/panel05b.webp" media="(width < 700px)"><img src="./image/panel05.webp" draggable="false"></picture></article>',
			'<article><picture><source srcset="./image/panel06b.webp" media="(width < 700px)"><img src="./image/panel06.webp" draggable="false"></picture></article>',
		]
	);
})();
動作環境(2024-01-09時点)
・Google Chrome 120
・Microsoft Edge 120
・Mozilla Firefox 122.0b6
・Apple Safari 17.1.2
いつもながらスイッチャー/スワイパーは自作しており、最近はCSSの機能が充実しているのでJavaScriptの記述量は半分程度でスイッチャー/スワイパーが書けるようになった。
この版は極力JavaScriptを使用せずにCSSの記述に重点を置き作成を試みたもので有るが、スワイプ操作等々を含めるとそれなりのJavaScriptコード量になってしまった。ただし実質200行足らずのコンパクト設計である。
この処理を使いたい方はソースコードを参考に自分好みのものに仕上げて欲しい。
スイッチャー/スワイパーはその都度顧客のニーズや状況に合わせて作り変えている。よってライブラリの様に使い易くすることは無いしパラメータ類はコード内に埋め込んでいる。
何らかのライブラリを使うと用途がそのライブラリの制御範囲に限定されてしまう為好きではないし、概ね巨大である。
その都度作る方がコードも最小限で軽量に仕上がるしメンテナンスできる。
ブラウザ互換で困ることも最近は少ない。JavaScriptは使い捨てが原則。
この記事は2024年1月当時の物です。
このサイトについてのお問い合わせはエーオーシステムまでお願いいたします。
ご使用上の過失の有無を問わず、本プログラムの運用において発生した損害に対するいかなる請求があったとしても、その責任を負うものではありません。