swiper 슬라이드 넘길때 유튜브 영상 자동재생되게 하는법

매출이 오르면 내리는 수수료! 지금 수수료센터에서 전자결제(PG)수수료 비교견적 신청해 보세요!
swiper 슬라이드 넘길때 유튜브 영상 자동재생되게 하는법

QA

swiper 슬라이드 넘길때 유튜브 영상 자동재생되게 하는법

본문

1. 메인 스와이퍼 코드


<div class="swiper swiperleft01">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <div>
        <iframe src="유튜브 영상 링크" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
       <div class="title_wrap"> <p>제목</p></div>  
      </div>
    </div>
    <div class="swiper-slide">
      <div>
        <iframe src="유튜브 영상 링크" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
       <div class="title_wrap"> <p>제목</p></div>  
      </div>
    </div>
  </div>
</div>
 
<script>
  var swiperTopNum2 = jQuery('.swiperleft02').find('.swiper-slide');
  var swiperSubNum2 = jQuery('.swiperBottom02').find('.swiperBottom02');
  var subSlide2 = new Swiper(".swiperBottom02", {
    slidesPerView: 2,
  slidesPerGroup: 4,
  spaceBetween: 10,
  grid: {
    fill: 'row',
    rows: 2
  },
  loop: false,
  slideToClickedSlide: true,
  watchSlidesProgress: true,
  pagination: {
        el: ".swiper-pagination",
        clickable: true
      },
  });
  var mainSlide2 = new Swiper(".swiperleft02", {
  effect:'fade',
  slidesPerView: 1,
  allowTouchMove:false,
  loop:true,
  thumbs: {
    swiper: subSlide2
  },
  on: {
    transitionStart: function(){
      
      var videos2 = document.querySelectorAll('video');
      Array.prototype.forEach.call(videos2, function(video2){
        video2.pause();
      });
    },
    
    transitionEnd: function(){
      
      var activeIndex2 = this.activeIndex;
      var activeSlide2 = jQuery('.swiperleft02').find('.swiper-slide:eq('+activeIndex2+')');
      var activeSlideVideo2 = activeSlide2.find('video')[0];
      activeSlideVideo2.currentTime = 0;
      activeSlideVideo2.play();
    
    },
  }
});
</script>

 

2. 서브 스와이퍼 코드

 


<div class="swiper swiperBottom01">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <div>
        <img src="/images/thum08.jpg" alt="">
         <div class="title_wrap"> <p>제목</p></div>  
      </div>
    </div>
    <div class="swiper-slide">
      <div>
        <img src="/images/thum09.jpg" alt="">
        <div class="title_wrap"> <p>제목</p></div>  
      </div>
    </div>
  </div>
  <div class="swiper-pagination"></div>
</div>

 

안녕하세요, 메인스와이퍼와 서브 스와이퍼를 연동하고, 서브 스와이퍼의 이미지를 누르면 메인 스와이퍼가 이동하고 영상이 재생되는 그런 코드를 짜봤습니다.

 

유지보수 중에 video 파일이 아니고 유튜브 링크를 올려달라고 하셔서 난항을 겪고있습니다. autoplay=1, mute=1 을 써도 영상 자동재생이 안됩니다...ㅠㅠ 슬라이드를 넘겼을 때 유튜브 영상 넣은 슬라이드에 멈추면 영상 재생되게끔 하는 방버이 있을까요?

이 질문에 댓글 쓰기 :

답변 1

다음을 참고 하셔서 원하시는 형식으로 구현하시면 가능하지 않을까 생각합니다.


// 메인 스와이퍼의 각 슬라이드에 해당하는 유투브 ID를 저장하는 배열 생성
var videoIds = ["YouTube 비디오 ID1", "YouTube 비디오 ID2", ...];

// 각 슬라이드가 활성화될 때 해당 비디오를 재생하도록 구현
var players = [];
function onYouTubeIframeAPIReady() {
    for (var i = 0; i < videoIds.length; i++) {
        players[i] = new YT.Player('player' + i, {
            height: '360',
            width: '640',
            videoId: videoIds[i],
            events: {
                'onReady': onPlayerReady,
            }
        });
    }
}
function onPlayerReady(event) {
    // 비디오가 준비되면 아무것도 하지 않음
}

// 메인 스와이퍼의 transitionEnd 이벤트에 이벤트 핸들러를 추가하여 활성화된 슬라이드의 인덱스를 확인하고 해당 비디오를 재생
 
transitionEnd: function() {
    var activeIndex2 = this.activeIndex;
    players.forEach(function(player, index) {
        if (index === activeIndex2) {
            player.playVideo();
        } else {
            player.pauseVideo();
        }
    });
}

 

답변을 작성하시기 전에 로그인 해주세요.
전체 73
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT