我正试图通过点击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()
})
});
}
这是我的小提琴。如有任何帮助,将不胜感激
http://jsfiddle.net/sghoush1/zmqj6h1b/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() {
//...
}