我的网站有一个包含大量文字的索引页面和一个触发模态窗口的按钮,您可以在其中看到YouTube视频。在正常情况下(人们阅读页面文本,然后实现按钮,他们点击按钮)没有问题,但是当我在页面加载后(或在...期间)单击按钮时,会出现模态窗口但是其中没有视频,当然FireBug会抛出错误,说明视频尚未加载。
我不介意在按下按钮后等待视频加载,我想按下按钮并且100%的时间观看视频,但我不知道如何开始加载Api我想要的那一刻。你有一些相关的代码片段:
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player("player", {
height: $('#modalvideo').height()*0.9,
width: $('#modalvideo').width()*0.9,
videoId: "NeeTGjp5-Ag"
})
}
$(document).ready(function() {
$(".youtube").on("click", function(e) {
e.preventDefault();
// THIS IS THE PLACE WHERE I WOULD WANT TO LOAD THE YOUTUBE API, EVEN IF I HAVE TO WAIT
$("#modalvideo").modal("show");
player.playVideo();
});
});
谢谢大家!
答案 0 :(得分:1)
这样的事情可能(对不起,它似乎不适用于stackoverflow的片段iframe - 您可以尝试使用jsfiddle代替:https://jsfiddle.net/hzmdj2m6/)?
var player;
var playWhenReady = false;
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady() {
console.log('API is ready');
player = new YT.Player("player", {
height: $('#modalvideo').height() * 0.9,
width: $('#modalvideo').width() * 0.9,
videoId: "NeeTGjp5-Ag",
playerVars: {
origin: 'http://stacksnippets.net'
},
events: {
onReady: onYouTubePlayerReady
}
})
}
function onYouTubePlayerReady(e) {
console.log('Player is ready');
player.isReady = true;
if (playWhenReady) {
playVideo();
}
}
function playVideo() {
console.log('playVideo');
if (player && player.playVideo) {
console.log('now');
//$("#modalvideo").modal("show");
player.playVideo();
return;
} else {
console.log('postpone');
playWhenReady = true;
}
}
$(document).ready(function() {
$(".youtube").on("click", function(e) {
e.preventDefault();
playVideo();
});
});

#modalvideo {
width: 300px;
height: 300px;
background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="youtube">play</a>
<div id="modalvideo">
<div id="player"></div>
</div>
&#13;
或使用排队:https://developers.google.com/youtube/iframe_api_reference#Queueing_Functions