2 回答
TA贡献1898条经验 获得超8个赞
您应该只在播放时获取时间,并在暂停时保存。将当前时间设置为本地存储播放时暂停的时间。像这样:
var vid = document.getElementById("myVideo");
function getCurTime() {
return vid.currentTime;
}
var isPlaying = false;
var PausedTime;
function PlayVideo() {
var change = document.getElementById("PlayVideo");
//Get the saved time from local storage
var PausedTime = localStorage.getItem('CaptureTime');
if (isPlaying) {
vid.pause();
//Storing the paused time to local storage
localStorage.setItem('CaptureTime', getCurTime());
change.innerHTML = "Play";
}
else {
vid.currentTime = PausedTime;
vid.play();
change.innerHTML = "Pause";
}
isPlaying = !isPlaying;
}
<video id="myVideo" width="300" height="300" controls>
<source src="Bunny.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video><br/>
<button onclick="PlayVideo()" type="button" id="PlayVideo">Play</button>
TA贡献1824条经验 获得超5个赞
要在 JavaScript 中暂停和播放视频,您实际上不需要将时间保存到本地存储。话虽这么说,如果你仍然想这样做,你只需要记住这些行:
localStorage.setItem('CaptureTime', getCurTime());
PausedTime = localStorage.getItem('CaptureTime');
vid.currentTime = PausedTime;
另外,当我尝试你的代码时,它不会将播放更改为暂停,所以我做了一些调整。
这就是我实现这一切的方式:
<html>
<body>
<button id="controls" onclick="play()" type="button">Play Video</button><br>
<video id="myVideo" width="320" height="176">
<source src="Bunny.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
<script>
var vid = document.getElementById("myVideo");
var isPlaying = false; //or this could be: var isPaused = vid.paused;
function play() {
if(!isPlaying){
vid.play();
document.getElementById("controls").innerHTML = "Pause Video";
}
else{
vid.pause();
document.getElementById("controls").innerHTML = "Play Video";
}
isPlaying = !isPlaying;
}
</script>
</body>
</html>
添加回答
举报