开始
播放视频后的每一秒,我希望它运行称为showComments的功能
为了确保它每秒都在运行,我只是添加了
alert(getCurrentTime().toFixed());
但是,它甚至没有运行:(
如何使此运行显示评论每秒运行一次?
这是演示和代码。
演示:https://jsfiddle.net/f0buajyz/
<div id="player"></div>
<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 onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '270',
width: '480',
videoId: 'mzIdhSTHJts',
});
}
var fixedTimeHtml5Youtube = 0;
function getStatus(){
if(player.getCurrentTime().toFixed() != fixedTimeHtml5Youtube){
alert(getCurrentTime().toFixed());
showComments(player.getCurrentTime().toFixed());
fixedTimeHtml5Youtube = player.getCurrentTime().toFixed();
}
}
</script>
您可以使用 setInterval 每 1000ms(1s) 运行一次函数,并结合 onStateChange
事件。每当事件触发时,它都会检查视频是否正在播放。如果它正在播放,它会每秒开始调用 showComments
函数。否则,它将停止间隔。
工作小提琴:https://jsfiddle.net/crisbeto/f0buajyz/4/
.HTML:
<div id="player"></div>
<textarea id="output"></textarea>
JavaScript:
var tag = document.createElement('script');
var player = null;
var interval = null;
tag.src = "https://www.youtube.com/iframe_api";
document.body.appendChild(tag);
window.onYouTubeIframeAPIReady = function(){
player = new window.YT.Player(document.getElementById('player'), {
height: '270',
width: '480',
videoId: 'mzIdhSTHJts',
events: {
onStateChange: function(event){
callback(event);
}
}
});
}
function callback(event){
var playerStatus = event.data;
// player is playing
if(playerStatus === 1){
interval = setInterval(showComments, 1000);
// player is stopped
}else if(interval){
clearInterval(interval);
}
}
function showComments(){
document.getElementById('output').value += "n showComments called.";
}