2
我試圖通過使用Youtube API控制回放的能力來動態加載YouTube視頻(在頁面加載後點擊時生成iframe)。Youtube API動態iFrame
我發現的是,如果加載API時頁面上不存在iFrame,我似乎無法讓控件工作。我究竟做錯了什麼? (我想避免一個解決方案,包括加載時在頁面上顯示iframe)
下面是一些示例代碼:https://jsfiddle.net/nu1y9oe8/5/(單擊黑色框以生成iframe並播放視頻。一旦視頻正在播放嘗試點擊暫停按鈕)
如何將API綁定到iframe,一旦它已經在點擊創建,以便暫停按鈕的作品?
'use strict';
var player;
// Call the youtube api
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);
// Is the api ready
function onYouTubeIframeAPIReady() {
console.log('api is ready');
}
(function() {
var youtube = document.querySelectorAll(".youtube");
for (var i = 0; i < youtube.length; i++) {
youtube[i].addEventListener("click", function() {
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "test-api");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "");
iframe.setAttribute("src", "https://www.youtube.com/embed/"+ this.dataset.embed +"?rel=0&showinfo=0&autoplay=1&enbalejsapi=1");
this.innerHTML = "";
this.appendChild(iframe);
player = new YT.Player('test-api');
console.log(player);
});
}
var pause = document.querySelector('.pause');
pause.addEventListener('click', function() {
player.pauseVideo();
});
})();
任何幫助將不勝感激, 謝謝!
請你詳細說明... – 2016-10-03 07:42:15