在我的网站上,后台播放视频。当我要转到另一个页面时,如何在同一点恢复视频?使用 ajax 刷新页面。 我试图通过主页上的小脚本解决它:
<script>
var vid = document.getElementById("video");
vid.addEventListener("canplay", function(e) {
var currTime = this.currentTime;
this.play();
}, false
);
</script>
另一个脚本,在另一个 html 页面上,我想在其中继续我的视频:
<script>
var vid = document.getElementById("myVideo");
vid.addEventListener("canplay", function(e) {
this.currentTime = currTime;
this.play();
}, false
);
</script>
我遇到下一个错误:
Uncaught ReferenceError: currTime is not defined
at HTMLVideoElement.<anonymous>
我对这个解决方案是否正确?如果我能修复这个错误,它会起作用吗?如果回答:是的,我如何将这个“currTime”全局化? 谢谢。
更新: 视频的 HTML 代码:
<video loop muted autoplay poster="../static/images/wallpaper.png" class="fullscreen-bg__video" id="video">
<source src="../static/videos/wallpaper.mp4" type="video/mp4">
<source src="../static/videos/wallpaper.webm" type="video/webm">
</video>
.fullscreen-bg__video {
position: absolute;
top: 0;
left: 0;
width: 100%;
margin:0;
}
在页面上,我得到暂停的视频相同的代码,但有另一个 id。
最佳答案
<script>
var vid = document.getElementById("video");
vid.addEventListener("canplay", function(e) {
localStorage.setItem("videoTime", this.currentTime);
this.play();
}, false
);
</script>
注意:localStorage.setItem("videoTime", this.currentTime)
仅完成 一次。您可以每秒使用 setInterval()
将时间设置为一个新值。
setInterval(() => {localStorage.setItem("videoTime", this.currentTime);},1000);
重新加载后获取项目:
<script>
var vid = document.getElementById("myVideo");
vid.addEventListener("canplay", function(e) {
if(localStorage.getItem("videoTime") !== null) {
this.currentTime = localStorage.getItem("videoTime");
}
this.play();
}, false
);
</script>
更新:
在我的机器上测试过。适用于任何 .html 文件。只需将其粘贴为脚本即可:
<script>
window.onload = () => {
var vid = document.getElementById("video");
if(localStorage.getItem("videoTime") !== null && localStorage.getItem("videoTime") !== undefined) {
vid.currentTime = localStorage.getItem("videoTime"); }
setInterval(() => {localStorage.setItem("videoTime", vid.currentTime);},1000);
</script>
- 在窗口加载后执行脚本。
- 获取 vid 作为 HTMLElement
- 检查是否存在键为
vidTime
的 localStorage 条目。 - 如果是,使用
vid.currentTime = localStorage.getItem("videoTime"); 设置视频时间
- 每秒更新一次新的视频时间:
setInterval(() => {localStorage.setItem("videoTime", vid.currentTime);},1000);
关于javascript - 带有背景视频的刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52413387/