我提前道歉,我对脚本编写不是很好,所以我希望这不是一个基本的请求。
我处于需要多个循环可点击的YouTube视频的情况。我不想使用可嵌入的播放列表循环选项,因为它有几秒钟的黑色,它会刷新播放列表中的视频,在这种情况下就是它自己。
我在这里找到了一些文章,向您展示如何使用数据属性动态创建多个视频,以及如何在YouTube视频中循环特定时间,但当我尝试将这些视频组合时,我收到错误,我假设是一个范围问题,但不知道如何解决。下面是我的代码,以及每个原始小提琴的链接。
我收到的错误是: “未捕获的ReferenceError:玩家未定义”
<div style="position: relative;display:block;width: fit-content;margin:0 auto;">
<a href="#"><div style="width: 100%;height:100%;position:absolute;"></div>
</a>
<div class="video-container">
<div data-id="YE7VzlLtp-4"></div>
</div>
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
function onYouTubeIframeAPIReady() {
var players = document.querySelectorAll('.video-container div')
for (var i = 0; i < players.length; i++) {
new YT.Player(players[i], {
videoId: players[i].dataset.id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
},
playerVars: {
'autoplay': 1,
'loop': 1,
'controls': 0,
'showinfo': 0,
'modestbranding': 1}
});
}
}
function onPlayerReady(event) {
loopStart();
players.playVideo();
}
function loopStart() {
players.seekTo(7); // Start at 7 seconds
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
setTimeout(loopStart, 5000); // After 5 seconds, restart the loop
}
}
</script>
使用数据属性示例的多个视频: https://jsfiddle.net/nightcoregirl/jyha6xj5/
循环示例: http://jsfiddle.net/pbosakov/Lo6gwtff/
提前感谢任何见解!
答案 0 :(得分:0)
您的具体问题是变量players
的范围。 players
中无法显示onPlayerReady
。要从event
对象中检索播放器,请使用event.target
:
的Javascript
function onYouTubePlayerAPIReady() {
players = document.querySelectorAll('.video-container div')
for (var i = 0; i < players.length; i++) {
var player = new YT.Player(players[i], {
videoId: players[i].dataset.id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
},
playerVars: {
'autoplay': 1,
'loop': 1,
'controls': 0,
'showinfo': 0,
'modestbranding': 1
}
});
}
}
function onPlayerReady(event) {
loopStart(event.target);
event.target.playVideo();
}
function loopStart(player) {
player.seekTo(7); // Start at 7 seconds
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
setTimeout(function() {
loopStart(event.target);
}, 5000); // After 5 seconds, restart the loop
}
}
HTML
<script src="https://www.youtube.com/iframe_api"></script>
<div class="video-container">
<div data-id="YE7VzlLtp-4"></div>
</div>
<div class="video-container">
<div data-id="3IXKIVZ9T-U"></div>
</div>
选中此fiddle