LOADING
ボタンクリック対応のシンプルなカルーセルを作ってみた[HTML]

概要


・横スクロールにscroll-snap-typeでスワイプによるカルーセルを作成(HTML、CSS)

https://developer.mozilla.org/ja/docs/Web/CSS/scroll-snap-type


・ボタンクリックによりスクロールの位置を変更することで、カルーセルを変更(javascript)



プログラム


・HTML

<div class="carousel">
  <div class="carousel-box">
    <span class="text">1</span>
    <button class="carousel-btn for-next">
  </div>
  <div class="carousel-box">
    <span class="text">2</span>
    <button class="carousel-btn for-next">
    <button class="carousel-btn for-prev">
  </div>
  <div class="carousel-box">
    <span class="text">3</span>
    <button class="carousel-btn for-prev">
  </div>
</div>


・css

.carousel{
  width:50vw;
  height:300px;
  margin:auto;
  overflow-x:auto;
  display:flex;//子要素を横一列に並べる
  scroll-snap-type: x mandatory;//スワイプによるスクロール
  scroll-behavior: smooth;//スワイプによるスクロール
  -webkit-overflow-scrolling: touch;//スワイプによるスクロール
}
.carousel::-webkit-scrollbar {
  display: none;//スクロールバーの非表示
}
.carousel-box{
  flex: 0 0 auto;//幅いっぱいに広げる
  width:100%;
  height:100%;
  position:relative;
  background:grey;

  scroll-snap-align: start;//スワイプによるスクロール
}
.carousel-btn{
  position:absolute;
  width:10%;
  top:0;
  bottom:0;
  background:white;
  border:none;
  opacity:0.5;
  cursor:pointer;
}
.for-next{
  right:0;//右端
}
.for-prev{
  left:0;//左端
}
.text{
  font-size:30px;
  color:white;
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
}


・javascript

document.addEventListener('click', function(e) {
  if(e.target.classList.contains('carousel-btn')) {
    var carousel = e.target.closest('.carousel');//carouselを取得
    var carousel_box = e.target.closest('.carousel-box');//クリックした親要素のcarousel-boxを取得
    
    if(e.target.classList.contains('for-next')){
      var width = carousel_box.offsetWidth;//boxの幅を取得
      var from_left = carousel.scrollLeft//現在のスクロール位置を取得(左端から)
      carousel.scrollLeft = from_left + width;//新しいスクロール位置を設定
    }else if(e.target.classList.contains('for-prev')){
      var width = carousel_box.offsetWidth;//boxの幅を取得
      var from_left = carousel.scrollLeft//現在のスクロール位置を取得(左端から)
      carousel.scrollLeft = from_left - width;//新しいスクロール位置を設定
    }
  }
});


サンプルはこちら

https://codepen.io/pen?template=ExLBxpB

favorite
chat_bubble 0
プロモーション