我正在尝试在页面上嵌入多个YouTube视频,每个视频都有自己的叠加和播放按钮,点按后会隐藏相关的叠加层并播放视频。
我可以让它适用于单个视频,但当我尝试添加更多内容并循环播放视频时,onPlayerReady函数似乎没有被调用。
https://codepen.io/anon/pen/mqeZgX
这是我的javascript
// Inject YouTube API script
const tag = document.createElement('script');
tag.src = '//www.youtube.com/player_api';
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
const players = document.querySelectorAll('.js-video-embed > iframe');
const playButtons = document.querySelectorAll('.video__button');
const overlays = document.querySelectorAll('.video__overlay');
window.onYouTubePlayerAPIReady = () => {
for (var i = 0; i < players.length; i++) {
new YT.Player(players[i], {
events: {
'onReady': onPlayerReady
},
});
}
};
function onPlayerReady() {
for (var i = 0; i < players.length; i++) {
// bind events
playButtons[i].addEventListener('click', () => {
players[i].playVideo();
overlays[i].style.display = 'none';
});
}
}
提前感谢您提供的任何指示!