我的网页上有一个计时器,在youtube视频开始后计时10秒。当计时器完成时,a启用。我也想暂停一下如果用户在这10秒内暂停/恢复视频,则恢复计时器。
我的代码如下所示:
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('ytvideo', {
height: '390',
width: '640',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
timerid = setTimeout(enableButtons, 10000)
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PAUSED) {
// pause & resume ?
}
}
function enableButtons() {
document.getElementById("push").disabled = false;
document.getElementById("next").disabled = false;
}
答案 0 :(得分:0)
您需要记下开始时间,如果视频暂停,请记下暂停时间,计算已用时间,重新启动时创建一个新的setTimeout
10000-{previous elapsed time}
1}}
希望下面的代码能够很好地展示这一点,以便您与代码集成。有很多"绒毛"在这里写一个演示 - 对你有用的一些东西我会用评论来围绕。
var timeId;
var startTime;
var pauseTime;
$('#start').on('click',function(){
// when your video starts make a note of the time
startTime = Date.now();
timerId = setTimeout(complete,10000);
// Ignore below
out("The timer is running for 10000ms");
$('#pause').prop('disabled',false);
$(this).prop('disabled',true);
});
$('#pause').on('click',function(){
// When user pauses video, clear the timeout and make a note of pause time
clearTimeout(timerId);
pauseTime = Date.now();
// Ignore below
out("The timer is paused with " + (10000-(pauseTime-startTime)) + "ms remaining");
$('#resume').prop('disabled',false);
$(this).prop('disabled',true);
});
$('#resume').on('click',function(){
// When user resumes, calculate remaining time and start a new timeout
var remaining = (10000-(pauseTime-startTime));
setTimeout(complete,remaining);
// ignore below
out("The timer is running for " + remaining + "ms");
$('#pause').prop('disabled',false);
$(this).prop('disabled',true);
})
// Ignore below
function complete(){
out("The timer is complete");
$('#start').prop('disabled',false);
$('#pause').prop('disabled',true);
}
function out(msg){
$('#output').html(msg);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start</button>
<button id="pause" disabled>Pause</button>
<button id="resume" disabled>Resume</button>
<div id="output"></div>
&#13;