我制作了一个网站,它通过数据库中的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时,我没有遇到此问题,但我不知道如何在视频播放时以这种方式触发事件。
答案 0 :(得分:0)
首先,检查您用于加载播放器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>
请注意,我们仍然会动态加载播放器库,以避免竞争条件。