点击jQuery停止youtube视频播放

时间:2017-07-27 20:14:23

标签: jquery youtube

当我点击另一个标签时,我试图停止youtube视频,但它似乎只在第二轮工作。

<!-- click on these to switch the videos -->    
<div class="home-video-item" data-tab="tab-1">
    <img src="https://www.image.com"/>
</div>
<div class="home-video-item" data-tab="tab-2">
    <img src="https://www.image.com"/>
</div>

<!-- video boxes -->
 <div id="tab-1" class="home-video-content current">
    <iframe width="500" height="281" src="https://www.youtube.com/embed/Qs74-Utqw?feature=oembed" frameborder="0" allowfullscreen=""></iframe>

 </div><div id="tab-2" class="home-video-content current">
    <iframe width="500" height="281" src="https://www.youtube.com/embed/Qs74-Utqw?feature=oembed" frameborder="0" allowfullscreen=""></iframe>
 </div>



$('.home-video-item').on('click', function (e){
    var tab_id = $(this).attr('data-tab');
    var video = $("#"+tab_id).find("iframe").attr("src");

    $("#"+tab_id).find("iframe").attr("src",video);
})

小提琴:https://jsfiddle.net/8oy0odas/

1 个答案:

答案 0 :(得分:0)

您可以使用IFrame player api暂停视频player.pauseVideo()

<!-- click on these to switch the videos -->
<div class="home-video-item" data-tab="tab-1">
  video 1 play
</div>
<div class="home-video-item" data-tab="tab-2">
  video 2 play
</div>

<!-- video boxes -->
<div id="tab-1" class="home-video-content current">
  <iframe id="ytplayer0" width="500" height="281" src="https://www.youtube.com/embed/x6kqVusK26c?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
</div>

<div id="tab-2" class="home-video-content current">
  <iframe id="ytplayer1" width="500" height="281" src="https://www.youtube.com/embed/x6kqVusK26c?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
</div>

Javascript in body:

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var players = new Array();
var iframes = document.getElementsByTagName("iframe");

function onYouTubeIframeAPIReady() {
  for (i = 0; i < iframes.length; i++) {
    players[i] = new YT.Player(iframes[i].id, {});
  }
}

$('.home-video-item').on('click', function(e) {
  for (i = 0; i < iframes.length; i++) {
    players[i].pauseVideo();
  }
})

每次点击一个标签,所有播放器都会暂停。

Here是一个工作小提琴