此jsfiddle http://jsfiddle.net/StephanieQ/oo1g1762/
// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement("script");
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player("player", {
"height": "315",
"width": "560",
"videoId": "bHQqvYy5KYo",
"events": {
"onReady": onPlayerReady,
"onStateChange": onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event){
var time;
time = player.getCurrentTime();
$("#timeHolder").text(time);
}
我使用youTube的播放器对象方法player.getCurrentTime();找出嵌入式youTube视频的时间。正如您所看到的,每次更改玩家状态时,&#34;时间&#34;重新定义并插入timeHolder div中。有没有办法让时间&#34;是否连续定义,以便它与当前时间匹配并在更新时插入div中? (不是由玩家状态改变引发的?)
更重要的是,我正在玩这个,因为我希望能够使用youTube视频上的当前时间与其他外部脚本进行交互,我该如何将其设为全局?
答案 0 :(得分:3)
使用setInterval()
重复此功能。当even.data等于1表示youtube正在播放时,让函数重复。否则不播放,然后使用clearInterval()
停止重复功能。
var myTimer;
function onPlayerStateChange(event){
if(event.data==1) { // playing
myTimer = setInterval(function(){
var time;
time = player.getCurrentTime();
$("#timeHolder").text(time);
}, 100); // 100 means repeat in 100 ms
}
else { // not playing
clearInterval(myTimer);
}
}
请参阅jsfiddle here