javascript - 带有背景视频的刷新页面

标签 javascript ajax html html5-video video-player

在我的网站上,后台播放视频。当我要转到另一个页面时,如何在同一点恢复视频?使用 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> 
  1. 在窗口加载后执行脚本。
  2. 获取 vid 作为 HTMLElement
  3. 检查是否存在键为 vidTime 的 localStorage 条目。
  4. 如果是,使用 vid.currentTime = localStorage.getItem("videoTime"); 设置视频时间
  5. 每秒更新一次新的视频时间:setInterval(() => {localStorage.setItem("videoTime", vid.currentTime);},1000);

关于javascript - 带有背景视频的刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52413387/

相关文章:

javascript - Node.js - 诊断 "(node) warning: Recursive process.nextTick detected."

javascript - 如何拆分数组并仅将特定值保存到数据库中? Laravel 与 Ajax

javascript - jQuery $.post 返回不完整的数据

html - 将VS2019中的WebBrowser控件替换为Mozilla浏览器控件(v1.7.12)

html - 如何清理微软 html 文档?

html - divs 按钮悬停鼠标行为不正确

javascript - 在 CMB Metabox 上添加选项卡

javascript - 从 Json 对象中删除双引号

javascript - 页面加载后仅重新加载一个(切换)文件

Jquery .on() 方法不适用于动态创建的元素