我正试图通过Youtube API找到一种方法,在另一个播放时暂停一个视频,我在同一页面上有多个Youtube嵌入。是否有一个简单的代码,我完全错过了?
<div id="video_youtube" style="min-height:600px; margin-top:1%;">
<iframe id='player1' style="margin-right:2%; padding-bottom:1%;" width="500px" height="281px" src="http://www.youtube.com/embed/rZye11nxOOQ" frameborder="0" allowfullscreen>
</iframe>
<iframe id='player2' style="padding-bottom:1%;" width="500px" height="281px" src="http://www.youtube.com/embed/8Q89hEnkYH4" frameborder="0" allowfullscreen>
</iframe>
</div>
我找到了一个代码,它可以让你对两个视频做同样的事情,但我认为如果我必须添加更多的视频,这段代码太手动,将变得更长和复杂。
<div id="player1"></div>
<div id="player2"></div>
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player1', {
height: '293',
width: '520',
videoId: 'zXV8GMSc5Vg',
events: {
'onStateChange': onPlayerStateChange
}
});
player2 = new YT.Player('player2', {
height: '293',
width: '520',
videoId: 'LTy0TzA_4DQ',
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
stopVideo(event.target.a.id);
}
}
function stopVideo(player_id) {
if (player_id == "player1") {
player2.stopVideo();
} else if (player_id == "player2") {
player1.stopVideo();
}
}
</script>
如果你创建一个包含所有玩家对象的对象,并确保引用每个玩家的属性名称与该玩家的ID相匹配会怎么样?然后你的stop方法可以做一个简单的javascript for…在…循环(循环遍历属性名而不是值):
<div id="player1"></div>
<div id="player2"></div>
<!-- add as many as you need -->
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player={};
function onYouTubeIframeAPIReady() {
player.player1 = new YT.Player('player1', {
height: '293',
width: '520',
videoId: 'zXV8GMSc5Vg',
events: {
'onStateChange': onPlayerStateChange
}
});
player.player2 = new YT.Player('player2', {
height: '293',
width: '520',
videoId: 'LTy0TzA_4DQ',
events: {
'onStateChange': onPlayerStateChange
}
});
// add more here, ensuring that in player.[whatever] the 'whatever' is the same as the ID. You could very easily script this process as well so you don't repeat yourself.
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
stopVideos(event.target.a.id);
}
}
function stopVideos(player_id) {
for (p in player) {
if (p!==player_id) {
player[p].stopVideo(); // all videos will stop playing except the one that triggered the event
}
}
}
</script>