我知道这个问题曾经被问过。但是,答案已经过时,我还需要多个iframe播放器的其他信息。
我遵循了Google Developers website中的代码。但是,当我尝试在event.target.playVideo();
内致电onPlayerReady(event) function
时,第一次加载页面时视频无法播放。
我也收到了此错误消息GET https://i.ytimg.com/vi_webp/M7lc1UVf-VE/sddefault.webp?v=516f0b27 404
现在,我以2个视频为例,分别介绍Play video 1
,Stop video 1
,Play video 2
和Stop video 2
的工作。当有很多视频时,如何设置代码,使其嵌入起来更紧凑?谢谢您的帮助。
var tag = document.createElement('script');
tag.id = 'iframe-demo';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1;
var player2;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('existing-iframe-example1', {
events: {
'onReady': onPlayerReady1
}
});
player2 = new YT.Player('existing-iframe-example2', {
events: {
'onReady': onPlayerReady2
}
});
}
function onPlayerReady1(event) {
event.target.playVideo();
$(function() {
$('#play-btn1').on('click', function() {
event.target.playVideo();
});
$('#stop-btn1').on('click', function() {
event.target.stopVideo();
});
});
}
function onPlayerReady2(event) {
event.target.playVideo();
$(function() {
$('#play-btn2').on('click', function() {
event.target.playVideo();
});
$('#stop-btn2').on('click', function() {
event.target.stopVideo();
});
});
}
.control { margin-bottom: 30px; }
.play-btn, .stop-btn { display: inline-block; margin: 10px 20px; color: blue; cursor: pointer; }
.play-btn:hover, .stop-btn:hover { color: orange; cursor: pointer; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<iframe id="existing-iframe-example1" width="640" height="360" frameborder="0" allowfullscreen src="https://www.youtube.com/embed/M7lc1UVf-VE?autoplay=1&enablejsapi=1&controls=1&rel=0&color=white"></iframe>
<div class="control">
<div id="play-btn1" class="play-btn">Play video 1</div>
<div id="stop-btn1" class="stop-btn">Stop video 1</div>
</div>
<iframe id="existing-iframe-example2" width="640" height="360" frameborder="0" allowfullscreen src="https://www.youtube.com/embed/5a2oZwB6zX0?autoplay=1&enablejsapi=1&controls=1&rel=0&color=white"></iframe>
<div class="control">
<div id="play-btn2" class="play-btn">Play video 2</div>
<div id="stop-btn2" class="stop-btn">Stop video 2</div>
</div>