アフィリエイト広告を利用しております。
参考サイトの記載がある場合はそちらの方がより詳しく記載説明がされているのでぜひそちらもご覧ください。
そのままコピペしても反映されないものもあります。サイトごとに変えないといけない箇所がありますので修正してください。

CSS HTML JavaScript

画像を横に無限ループさせる方法(JavaScript)

画像を横に無限ループさせる処理をJavaScriptで実装します。
自作なので色々と不具合等あると思います。
[animation]を使わないのはなぜかと言うと、画像が表示されない(存在はしてる)状態があったからになります。
また、本気で使うなら「Swiper.js」や「slick.js」使った方が無難と思います。(なんで自作したのだろうか私は…)
クリックすることで画像が止まり、ドラックすることで移動するようにもしております。
自作でホップアップ処理を作るとも併用できるのでお試しください。

  • 振り向きねこちゃん
  • 寝そべりねこちゃん
  • どすけべねこちゃん
  • マリトッツォねこちゃん
  • 振り向きねこちゃん
  • 寝そべりねこちゃん
  • どすけべねこちゃん
  • マリトッツォねこちゃん
let animationId = null;
let totalWidth = 0;
let pos = 0;
let speed = 0;

let isDragg = false;
let isDragging = false;
let dragStartX = 0;
let draggedX = 0;
let allowClick = true;


document.addEventListener('DOMContentLoaded', function() {

	const element = document.querySelector('.loop-img');

	// マウスイベントの設定
    element.addEventListener('mousedown', startDrag);
    element.addEventListener('mousemove', drag);
    element.addEventListener('mouseup', endDrag);
    element.addEventListener('mouseleave', endDrag);
    
	// タッチイベントの設定
	element.addEventListener('touchstart', startDrag);
	element.addEventListener('touchmove', drag);
	element.addEventListener('touchend', endDrag);
	element.addEventListener('touchcancel', endDrag);
	
	// 画像ループ処理
    loop();
});

//----------------------------------------------------------
//  ループ処理
//----------------------------------------------------------
function loop() {
    if (!isDragging) {

	const element = document.querySelector('.loop-img');
	const items = document.querySelectorAll('.loop-img-item');

    initializeSpeed();
    calculateTotalWidth();

    pos -= speed;

    if (pos <= -totalWidth / 2) {
        let protrude = (-totalWidth / 2) - pos;
        pos = 0 + -protrude;
    }

    element.style.transform = `translateX(${pos}px)`;
}
    animationId = requestAnimationFrame(loop);
}


//----------------------------------------------------------
//  Speedの初期化
//----------------------------------------------------------
function initializeSpeed() {
    if (window.matchMedia('(max-width: 767px)').matches) {
        speed = 3;
    } else {
        speed = 2;
    }
}


//----------------------------------------------------------
//  totalWidthの計算
//----------------------------------------------------------
function calculateTotalWidth() {
	const items = document.querySelectorAll('.loop-img-item');

    totalWidth = 0;
    
    items.forEach(item => {
        const style = getComputedStyle(item);
        const width = item.clientWidth;
        const marginLeft = parseFloat(style.marginLeft);
        const marginRight = parseFloat(style.marginRight);
        const paddingLeft = parseFloat(style.paddingLeft);
        const paddingRight = parseFloat(style.paddingRight);

        totalWidth += width + marginLeft + marginRight + paddingLeft + paddingRight;
    });
}

//----------------------------------------------------------
//  Drag 開始処理
//----------------------------------------------------------
function startDrag(e) {
    isDragg = true;
    isDragging = false;
    allowClick = true;
    dragStartX = e.clientX || e.touches[0].clientX;
}

//----------------------------------------------------------
//  Drag 中処理
//----------------------------------------------------------
function drag(e) {
    if (isDragg) {
    
    	isDragging = true;
    	allowClick = false;
    	
		const element = document.querySelector('.loop-img');
		const items = document.querySelectorAll('.loop-img-item');

		initializeSpeed();
		calculateTotalWidth();

		let client = e.clientX || e.touches[0].clientX;
		draggedX = client - dragStartX;
		dragStartX = client;
		pos += draggedX;
		

		if (pos <= -totalWidth / 2) {
			let protrude = (-totalWidth / 2) - pos;
			pos = 0 + -protrude;
		} else if( 0 <= pos ){
			let protrude = 0 + pos;
			pos = (-totalWidth / 2) + protrude;
		}
		

		element.style.transform = `translateX(${pos}px)`;
    
    }
}

//----------------------------------------------------------
//  Drag 終了処理
//----------------------------------------------------------
function endDrag() {
	if( isDragging ) {
        allowClick = false;
	} else {
	    allowClick = true;
	}
	isDragg = false;
	isDragging = false;
}
<div class="loop-img-container">
<div class="loop-img">
<ul class="loop-img-list">
<li class="loop-img-item"><img src="/wp-content/uploads/2024/12/01.png" alt="振り向きねこちゃん" width="370" height="320" class="aligncenter size-full wp-image-142" /></li>
<li class="loop-img-item"><img src="/wp-content/uploads/2024/12/04.png" alt="寝そべりねこちゃん" width="370" height="320" class="aligncenter size-full wp-image-143" /></li>
<li class="loop-img-item"><img src="/wp-content/uploads/2024/12/01-1.png" alt="どすけべねこちゃん" width="370" height="320" class="aligncenter size-full wp-image-144" /></li>
<li class="loop-img-item"><img src="/wp-content/uploads/2024/12/07.png" alt="マリトッツォねこちゃん" width="370" height="320" class="aligncenter size-full wp-image-145" /></li>
</ul>
<ul class="loop-img-list">
<li class="loop-img-item"><img src="/wp-content/uploads/2024/12/01.png" alt="振り向きねこちゃん" width="370" height="320" class="aligncenter size-full wp-image-142" /></li>
<li class="loop-img-item"><img src="/wp-content/uploads/2024/12/04.png" alt="寝そべりねこちゃん" width="370" height="320" class="aligncenter size-full wp-image-143" /></li>
<li class="loop-img-item"><img src="/wp-content/uploads/2024/12/01-1.png" alt="どすけべねこちゃん" width="370" height="320" class="aligncenter size-full wp-image-144" /></li>
<li class="loop-img-item"><img src="/wp-content/uploads/2024/12/07.png" alt="マリトッツォねこちゃん" width="370" height="320" class="aligncenter size-full wp-image-145" /></li>
</ul>
</div>
</div>
img::active {
    cursor: grabbing !important;
}
.p-entry__body ul {
    margin-left: 0px;
}

.loop-img-container {
    overflow: hidden;
}

.loop-img {
	display: flex;
    will-change: transform;
}

.loop-img-list {
    display: flex;
    list-style: none;
    padding: 0;
    list-style-type: none !important;
    margin-left: initial;
    user-select: none;
}

.loop-img-item {
    width: calc(100vw / 4);
    margin: 0 10px;
    text-align: center;
    font-weight: 900;
}

.loop-img-item img {
    width: 100%;
    pointer-events: none; 
    user-select: none;
}

おすすめ記事

1
制作理由 ワードプレスのクラシックエディタを直接使っているといつも思うことがありました [Tab]キー押して空白入れて見やすくインデントしたい! この記事を書くまでは入れないか、スペースキーを押して誤 ...
2
制作理由 ワードプレスのクラシックエディタを直接使っているといつも思うことがありました コード追加ボタンを自由に追加出来たら便利じゃない? この記事を書くまでは、クリップボード貼り付けアプリ[Clib ...
3
アプリ制作するに至った理由 納品代行の仕事をしていて思ったことがあります 納品代行をしていると本当に様々なお客様から様々な商品が届きます その中でも特に注意しているのが、「見た目ほぼ同じだけど違う商品 ...

-CSS, HTML, JavaScript
-