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>
添加回答
舉報