[Bootstrap] 이미지 슬라이딩 컨트롤(carousel)


Open source/Bootstrap  2020. 3. 3. 19:39

안녕하세요. 명월입니다.


이 글은 Bootstrap에서 이미지 슬라이딩 컨트롤(carousel)에 대한 글입니다.


웹 사이트에서 이미지를 나열할 때가 있습니다. 그러나 위 아래로 브라우저의 스크롤을 이용해서 나열하거나 왼쪽 오른쪽의 스크롤을 이용해서 나열하게 되면 꽤 조작하기가 힘듭니다.

그래서 슬라이딩 형식으로 왼쪽에서 오른쪽으로 나열하는 컨트롤이 있는데 그것이 carousel, 이미지 슬라이딩 컨트롤입니다.


링크 - https://getbootstrap.com/docs/3.4/javascript/#carousel

<!DOCTYPE html>	
<html>	
<head>	
  <title>title</title>	
  <!-- Bootstrap cdn 설정 -->	
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">	
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css">	
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">	
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>	
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>	
</head>	
<body>
  <!-- carousel를 구성할 영역 설정 -->
  <div style="width: 300px;margin: 100px;">
    <!-- carousel를 사용하기 위해서는 class에 carousel와 slide 설정한다. -->
    <!-- carousel는 특이하게 id를 설정해야 한다.-->
    <div id="carousel-example-generic" class="carousel slide" >
      <!-- carousel의 지시자 -->
      <!-- 지시자라고는 하는데 ol태그의 class에 carousel-indicators를 넣는다. -->
      <ol class="carousel-indicators">
        <!-- li는 이미지 개수만큼 추가하고 data-target은 carousel id를 가르킨다. -->
        <!-- data-slide-to는 순서대로 0부터 올라가고 0은 active를 설정한다. -->
        <!-- 딱히 이 부분은 옵션별로 설정하게 없다. -->
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
      </ol>
      <!-- 실제 이미지 아이템 -->
      <!-- class는 carousel-inner로 설정하고 role은 listbox에서 설정한다. -->
      <div class="carousel-inner" role="listbox">
        <!-- 이미지의 개수만큼 item을 만든다. 중요한 포인트는 carousel-indicators의 li 태그 개수와 item의 개수는 일치해야 한다. -->
        <div class="item active">
          <!-- 아미지 설정- -->
          <img src="https://tistory2.daumcdn.net/tistory/1041549/skin/images/nowonbuntistory.png" style="width:100%">
          <!-- 캡션 설정 (생략 가능) -->
          <!-- 글자 색은 검은색 -->
          <div class="carousel-caption" style="color:black;">
           명월 일지입니다.
          </div>
        </div>
        <div class="item">
          <img src="https://www.nowonbun.com/img/nowonbuntistory1.png" style="width:100%">
          <div class="carousel-caption" style="color:black;">
          明月開発ストーリ
          </div>
        </div>
      </div>
      <!-- 왼쪽 화살표 버튼 -->
      <!-- href는 carousel의 id를 가르킨다. -->
      <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
        <!-- 왼쪽 화살표 -->
        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
      </a>
      <!-- 오른쪽 화살표 버튼 -->
      <!-- href는 carousel의 id를 가르킨다. -->
      <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
        <!-- 오른쪽 화살표 -->
        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
      </a>
    </div>
  </div>
  <script>
    $(function(){
      // 이미지 슬라이드 컨트롤를 사용하기 위해서는 carousel를 실행해야한다.
      $('#carousel-example-generic').carousel({
        // 슬리아딩 자동 순환 지연 시간
        // false면 자동 순환하지 않는다.
        interval: 1000,
        // hover를 설정하면 마우스를 가져대면 자동 순환이 멈춘다.
        pause: "hover",
        // 순환 설정, true면 1 -> 2가면 다시 1로 돌아가서 반복
        wrap: true,
        // 키보드 이벤트 설정 여부(?)
        keyboard : true
	  });
	});
  </script>
</body>	
</html>
이름 유형 기본값 설명
interval number 5000 항목 자동 순환 사이의 지연 시간입니다. false 인 경우 회전식 슬라이드 쇼가 자동으로 순환되지 않습니다.
pause string | null "hover" hover로 설정하면 mouseenter에서 자동 순환이 일시 중지됩니다. null로 설정하면 자동 순환이 되지 않는다.
wrap boolean true 순환 설정, true면 1 -> 2가면 다시 1로 돌아가서 반복, false면 반복하지 않는다.
keyboard boolean true 키보드 이벤트 설정 여부(?)

carousel도 메소드가 있고 이벤트가 있습니다.

<!DOCTYPE html>	
<html>	
<head>	
  <title>title</title>	
  <!-- Bootstrap cdn 설정 -->	
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">	
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css">	
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">	
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>	
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>	
</head>	
<body>
  <!-- carousel를 구성할 영역 설절 -->
  <div style="width: 300px;margin: 100px;">
    <!-- carousel를 사용하기 위해서는 class에 carousel와 slide 설정한다. -->
    <!-- carousel는 특이하게 id를 설정해야 한다.-->
    <div id="carousel-example-generic" class="carousel slide" >
      <!-- carousel의 지시자 -->
      <!-- 지시자라고는 하는데 ol태그의 class에 carousel-indicators를 넣는다. -->
      <ol class="carousel-indicators">
        <!-- li는 이미지 개수만큼 추가하고 data-target은 carousel id를 가르킨다. -->
        <!-- data-slide-to는 순서대로 0부터 올라가고 0은 active를 설정한다. -->
        <!-- 딱히 이 부분은 옵션별로 설정하게 없다. -->
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
        <li data-target="#carousel-example-generic" data-slide-to="3"></li>
        <li data-target="#carousel-example-generic" data-slide-to="4"></li>
      </ol>
      <!-- 실제 이미지 아이템 -->
      <!-- class는 carousel-inner로 설정하고 role은 listbox에서 설정한다. -->
      <div class="carousel-inner">
        <!-- 이미지의 개수만큼 item을 만든다. 중요한 포인트는 carousel-indicators의 li 태그 개수와 item의 개수는 일치해야 한다. -->
        <div class="item active">
          <!-- 아미지 설정- -->
          <img style="width:100%">
          <!-- 캡션 설정 (생략 가능) -->
          <!-- 글자 색은 검은색 -->
          <div class="carousel-caption" style="color:black;">
           1 페이지
          </div>
        </div>
        <div class="item">
          <img style="width:100%">
          <div class="carousel-caption" style="color:black;">
          2 페이지
          </div>
        </div>
        <div class="item">
          <img style="width:100%">
          <div class="carousel-caption" style="color:black;">
          3 페이지
          </div>
        </div>
        <div class="item">
          <img style="width:100%">
          <div class="carousel-caption" style="color:black;">
          4 페이지
          </div>
        </div>
        <div class="item">
          <img style="width:100%">
          <div class="carousel-caption" style="color:black;">
          5 페이지
          </div>
        </div>
      </div>
      <!-- 왼쪽 화살표 버튼 -->
      <!-- href는 carousel의 id를 가르킨다. -->
      <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
        <!-- 왼쪽 화살표 -->
        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
      </a>
      <!-- 오른쪽 화살표 버튼 -->
      <!-- href는 carousel의 id를 가르킨다. -->
      <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
        <!-- 오른쪽 화살표 -->
        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
      </a>
    </div>
  </div>
  <!-- 이미지 슬라이드 순환을 개시 -->
  <button id="carousel_cycle">순환</button><br />
  <!-- 이미지 슬라이드 순환을 정지 -->
  <button id="carousel_pause">정지</button><br />
  <!-- 이미지 슬라이드를 이동할 수 -->
  <input type="number" id="carousel_number" min=1 max=5 value="1" >
  <!-- 이미지 슬라이드 이동 -->
  <button id="carousel_move">이동</button><br />
  <!-- 이미지 슬라이드 전 페이지 이동 -->
  <button id="carousel_prev">전</button>
  <!-- 이미지 슬라이드 다음 페이지 이동 -->
  <button id="carousel_next">후</button>
  <script>
    $(function(){
        // 이미지 설정
        $("img").attr("src","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABf4C/qc1gYQAAAAASUVORK5CYII=");
        // 이미지 슬라이드 설정
		$('#carousel-example-generic').carousel({
          // 순환 설정
          interval: 1000
          // 순환을 정지시킨다.
        }).carousel('pause');
	});
    // 이미지 슬라이드 순환을 개시
    $("#carousel_cycle").on("click", function() { 
      $('#carousel-example-generic').carousel('cycle'); 
    });
    // 이미지 슬라이드 순환을 정지
    $("#carousel_pause").on("click", function() { 
      $('#carousel-example-generic').carousel('pause'); 
    });
    // 이미지 슬라이드 이동
    $("#carousel_move").on("click", function() {
      var num = Number($("#carousel_number").val()) - 1;
      $('#carousel-example-generic').carousel(num); 
    });
    // 이미지 슬라이드 전 페이지 이동
    $("#carousel_prev").on("click", function() { 
      $('#carousel-example-generic').carousel('prev'); 
    });
    // 이미지 슬라이드 다음 페이지 이동
    $("#carousel_next").on("click", function() { 
      $('#carousel-example-generic').carousel('next'); 
    });
    $('#carousel-example-generic').on('slide.bs.carousel', function () {
      // 슬라이드 인스턴스 메서드가 호출되면 호출된다.
    });
    $('#carousel-example-generic').on('slid.bs.carousel', function () {
      // 회전식 슬라이드가 완료되면 호출된다.
    });
  </script>
</body>	
</html>



-----추가 2020년 4월 28일-----

carousel의 양 옆의 객체의 색을 바꾸고 싶다는 질문과 cycle의 방향 왼쪽에서 오른쪽이 아닌 오른쪽에서 왼쪽으로 이동하고 싶다는 질문이 있어서 추가 글을 작성합니다.


먼저 양 옆의 엘리먼트는 a.carousel-control로 select가 잡힙니다. style에 투명색을 추가하시면 표시가 안됩니다..

// 양 옆 컨트럴
a.carousel-control {
  // 투명색을 수정
  opacity: 0;
}

그리고 cycle 방향이 기본적으로 왼쪽에서 오른쪽으로 흐르는데 bootstrap에서는 이게 고정으로 소스를 작성했네요.

즉, bootstrap으로는 외부에서 설정할 방법이 없습니다.

그러면 전혀 방법이 없는게 아니고 똑같이 setInterval를 설정하면 됩니다.

$(function(){
  // 이미지 슬라이드 컨트롤를 사용하기 위해서는 carousel를 실행해야한다.
  let target = $('#carousel-example-generic').carousel({
    // 슬리아딩 자동 순환 지연 시간
    // false로 설정하여 bootstrap에서는 cycle를 움직이지 못하게 한다..
    interval: false,
    // hover를 설정하면 마우스를 가져대면 자동 순환이 멈춘다.
    pause: "hover",
    // 순환 설정, true면 1 -> 2가면 다시 1로 돌아가서 반복
    wrap: true,
    // 키보드 이벤트 설정 여부(?)
    keyboard : true
  });
  // Interval를 설정해서 next가 아닌 prev로 하면 반대로 움직인다.
  setInterval(function() {
    target.carousel('prev');
  }, 1000);
});

여기까지 Bootstrap에서 이미지 슬라이딩 컨트롤(carousel)에 대한 글이었습니다.


궁금한 점이나 잘못된 점이 있으면 댓글 부탁드립니다.