YouTube API - onPlayerStateChange [英] YouTube API - onPlayerStateChange
问题描述
我将YouTube API与Cyclone Slider结合使用。目标是在YouTube开始播放后暂停幻灯片播放。我正在使用以下代码,它运行良好:
I'm using the YouTube API in conjunction with Cyclone Slider. The goal is to pause the slideshow once the YouTube starts playing. I'm using the following code which works nicely:
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
<script>
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('video', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if(event.data === 1) {
$(".cycle-slideshow").cycle('pause');
}
if(event.data === 2) {
$(".cycle-slideshow").cycle('resume');
}
}
</script>
然而,它似乎只是如果我刷新页面,我会工作。如果我在页面之间导航并返回主页,它将不再有效。
However, it only seems to work if I do a refresh of the page. If I navigate between pages and return to the homepage, it will no longer work.
对于为什么会出现这种情况的任何建议?我已经尝试了一些我在谷歌上找到但却无法工作的建议。我在这一点上有点迷失。
Any suggestions for why this is the case? I've tried a few suggestions I found on Google but couldn't get any to work. I'm a little lost on this one.
任何帮助都将不胜感激。
Any help would be greatly appreciated.
推荐答案
尝试以下代码,它适用于我 -
Try the following code, it works for me -
function loadYouTube(targetId){
ytplayer = new YT.Player(targetId, {
events: {
'onStateChange': function(event){
/** YouTube API
-1 (unstarted)
0 (ended)
1 (playing)
2 (paused)
3 (buffering)
5 (video cued)
**/
if (event.data == 1) {
//do your work here
}
console.log(event.data)
}
}
});
}
这篇关于YouTube API - onPlayerStateChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!