我制作了一个网站,通过数据库中的id加载视频。我使用YoutubeAPI来嵌入播放器,但在IE播放器有时不加载。这是脚本。
<script>
var player;
var player_width = $(window).width() - 100;
var player_height = $(window).height() - 50;
$('.prev-next').height(player_height);
$('.prev-next-but').height(player_height);
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: player_width,
height: player_height,
videoId: '<?php echo $yt_id; ?>',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if(event.data === 0) {
document.forms["not_skipped"].submit();
}
}
当我使用简单的iframe时,我没有这个问题,但我不知道如何在视频结束时触发事件。
首先,检查你用来加载播放器API库的方法。如果使用脚本标记,则可能在定义onYouTubePlayerAPIReady
函数之前加载脚本,因此不会触发任何操作。为了避免这种竞争条件,您希望像这样加载库:
<script>
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 player;
var player_width = $(window).width() - 100;
var player_height = $(window).height() - 50;
$('.prev-next').height(player_height);
$('.prev-next-but').height(player_height);
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: player_width,
height: player_height,
videoId: '<?php echo $yt_id; ?>',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if(event.data === 0) {
document.forms["not_skipped"].submit();
}
}
</script>
现在,关于你提到的另一件事—-将玩家API连接到一个已经存在的iframe中是相当简单的;您只需要将iframe的ID传递给YT.Player
构造函数,并且不给它一个宽度,高度或视频ID,像这样:
<iframe id="myplayer" width="560" height="315" src="//www.youtube.com/embed/0kl3VNy0uAI?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<script>
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 player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('myplayer', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if(event.data === 0) {
document.forms["not_skipped"].submit();
}
}
</script>
请注意,我们仍然是动态加载播放器库,以避免竞争条件。