我正在尝试通过点击div加载YouTube视频。该想法是动态地将视频ID传递到播放器对象并将视频加载到帧中。我正在关注API,我看到他们正在传递dom然后加载JS。在我的情况下,这是不可能的。
这是我的JS
callMain ();
function playerApp(inputVid) {
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: inputVid,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
}
function backgroundOverlay(state){
var pageHeight = $( document ).height();
var overlay = '';
var wrapperHTML = ''
+ '<div class="videoplayer-wrapper">'
+ '<div id="player"></div>'
+ '<div class="videoplayer-close videoplayer-toggle">Close</div>'
+ '</div>';
if(state){
overlay = $('body').append('<div class="video-overlay-background" style="height:'+pageHeight+'px;"></div>').append(wrapperHTML);
}else{
overlay = $('.video-overlay-background').remove();
}
return overlay;
}
function callMain () //$(function(){
{
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var inputVid = '';
$('.videoplayer-toggle').on('click', function(){
inputVid = $(this).attr('data-youtubeid');
backgroundOverlay(true);
playerApp(inputVid)
$('.videoplayer-close').on('click', function(){
backgroundOverlay(false);
$('.videoplayer-wrapper').remove()
})
});
}
这是我的小提琴。任何帮助都将受到高度赞赏
答案 0 :(得分:1)
问题是永远不会触发onYouTubeIframeAPIReady
。您可以完全省略它,因为您在playerApp
内动态设置了播放器。请尝试以下方法:
function playerApp(inputVid) {
var player = new YT.Player('player', {
height: '390',
width: '640',
videoId: inputVid,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady() {
//...
}
function onPlayerStateChange() {
//...
}