マスクスライダーの実装方法jqueryなど無しで、CSSのclip-pathだけで動く方法
以下のコードを参考にしてください。
styleの.sliderのwidthとheightは、スライド画像の大きさにしてください。
<div class="slider"> <img src="https://hirocreate.com/wp-content/themes/seo/images/hirocreate/slide01.jpg" class="slide"> <img src="https://hirocreate.com/wp-content/themes/seo/images/hirocreate/slide02.jpg" class="slide"> <img src="https://hirocreate.com/wp-content/themes/seo/images/hirocreate/slide03.jpg" class="slide"> </div> <style> .slider { position: relative; width: 1200px; height: 480px; overflow: hidden; } .slide { position: absolute; width: 100%; height: 100%; object-fit: cover; top: 0; left: 0; clip-path: inset(0 100% 0 0); z-index: -1; transition: none; } .slide.shown { clip-path: inset(0 0 0 0); z-index: 0; transition: none; } .slide.animating { z-index: 1; transition: clip-path 1s ease; } </style> <script> const slides = document.querySelectorAll('.slide'); let currentIndex = 0; function initialize() { slides.forEach((slide, i) => { if (i === currentIndex) { slide.classList.add('visible'); slide.style.zIndex = 1; slide.style.clipPath = 'inset(0 0 0 0)'; } else { slide.classList.remove('visible', 'above'); slide.style.zIndex = 0; slide.style.clipPath = 'inset(0 100% 0 0)'; } }); } function nextSlide() { const total = slides.length; const prevIndex = currentIndex; currentIndex = (currentIndex + 1) % total; const prevSlide = slides[prevIndex]; const nextSlide = slides[currentIndex]; // 次のスライドを上に置きマスクで隠す状態に nextSlide.classList.add('above'); nextSlide.classList.remove('visible'); nextSlide.style.zIndex = 2; nextSlide.style.clipPath = 'inset(0 100% 0 0)'; // 1フレーム待ってマスクを外す(アニメーション開始) requestAnimationFrame(() => { requestAnimationFrame(() => { nextSlide.style.transition = 'clip-path 1s ease'; nextSlide.style.clipPath = 'inset(0 0 0 0)'; nextSlide.classList.add('visible'); }); }); // アニメ完了後、prevSlideを非表示化、nextSlideを背景化 setTimeout(() => { prevSlide.classList.remove('visible', 'above'); prevSlide.style.zIndex = 0; prevSlide.style.transition = 'none'; prevSlide.style.clipPath = 'inset(0 100% 0 0)'; nextSlide.style.zIndex = 1; nextSlide.style.transition = 'none'; }, 1100); } initialize(); setInterval(nextSlide, 3000); </script>
関連記事はこちら!
スポンサーリンク