编程语言
首页 > 编程语言> > javascript-使用jQuery播放/停止YouTube多个iframe播放器

javascript-使用jQuery播放/停止YouTube多个iframe播放器

作者:互联网

我正在尝试在一个页面上播放/停止多个YouTube iframe播放器.单击后我可以自动启动播放器(即通过名为loadYouTubeVideo(playerID)的自定义方法),但是我不确定如何从另一个函数调用中再次访问播放器对象(即通过称为unloadYouTubeVideo(playerID)的自定义方法) ))

这是我正在谈论的jsfiddle:http://jsfiddle.net/iwasrobbed/9Dj8c/3/

因此,每个玩家都开始了,但是即使包含它的div被隐藏,它也继续玩.

顺便说一句,我使用播放器的iframe版本是有原因的,因此回答“告诉我仅使用播放器的Flash对象嵌入版本”的答案对此问题不可接受.

如果jsfiddle不可用,请在此处输入代码:

<html>
<body>
<script>
$(document).ready(function(){
// YouTube Player API adapter
$.getScript('http://www.youtube.com/player_api');

loadYouTubePlayer = function(playerID) {
  the_player = new YT.Player(playerID, {
    events: { 'onReady': playYouTubeVideo }
  });
};  

unloadYouTubePlayer = function(playerID) {
  // This is the part that's broken
  $(playerID).stopVideo();
}; 

function playYouTubeVideo(event) {
  event.target.playVideo();
}

$('.show_player').click(function() {
    var idType = 'data-video-id';
    var id = $(this).attr(idType);

    $(this).fadeOut('fast', function() {
        $('.hidden_player['+idType+'='+id+']').fadeIn('fast', function() {
            loadYouTubePlayer('the_player'+id);
            $('.stop_player['+idType+'='+id+']').fadeIn('fast');
        });
    });
});

$('.stop_player').click(function() {
    var idType = 'data-video-id';
    var id = $(this).attr(idType);

    $(this).fadeOut('fast', function() {
        $('.hidden_player['+idType+'='+id+']').fadeOut('fast', function() {
            unloadYouTubePlayer('the_player'+id);
            $('.show_player['+idType+'='+id+']').fadeIn('fast');
        });
    });
});

});
</script>

<div class="hidden_player" data-video-id="0" style="display:none">
    <iframe id="the_player0" width="640" height="360" frameborder="0" src="http://www.youtube.com/embed/2ktsHhz_n2A" type="text/html"></iframe>
</div>
    <p><a href="#" class="show_player" data-video-id="0">Show video 0 and start playing automatically</a></p>
    <p><a href="#" class="stop_player" data-video-id="0" style="display:none">Stop video 0 from playing</a></p>

    <br/><br/>    

<div class="hidden_player" data-video-id="1" style="display:none">
    <iframe id="the_player1" width="640" height="360" frameborder="0" src="http://www.youtube.com/embed/2ktsHhz_n2A" type="text/html"></iframe>
</div>
    <p><a href="#" class="show_player" data-video-id="1">Show video 1 and start playing automatically</a></p>
    <p><a href="#" class="stop_player" data-video-id="1" style="display:none">Stop video 1 from playing</a></p>

</body>
</html>

解决方法:

我创建了一个函数,该函数可通过iframe父级的ID(在YT Frame API中指定)访问带框的YouTube视频,并执行JS API中定义的功能.

有关代码和详细的“问答”部分,请参见this answer.

我的代码将以这种方式实现:

callPlayer(playerID, "stopVideo");

标签:youtube,youtube-api,javascript,jquery
来源: https://codeday.me/bug/20191102/1989445.html