javascript - 使用 'this.currentTime' 获取视频的时间并将其重置为 'hover out' 上的起点

标签 javascript jquery video html5-video

我有一个视频库,我想在其中动态使用 URL 中的媒体片段时间作为海报。 将鼠标悬停在外时,我尝试将视频重置为初始开始位置 - 以确保海报处于 2 秒(在此特定示例中)而不是 0 秒。

this.load 可以工作,但是当整个视频再次加载时会产生糟糕的用户体验。

我的想法是将当前时间定义为一个变量(在视频开始播放之前)并在暂停视频时使用它。

但是我只是得到“ Uncaught ReferenceError :海报时间未定义”。

<video id="video">
  <source src="videourl.mp4#t=2" type="video/mp4">
</video>
const videos = document.querySelectorAll("video")

  videos.forEach(video => {

    video.addEventListener("mouseover", function () {
        var posterTime = this.currentTime;
        this.currentTime = 0;
        this.play()
    })
    
    video.addEventListener("mouseout", function () {
      this.currentTime = posterTime;
      this.pause();
    })
  })

请注意,我使用 Webflow,并且对 jQuery/Javascript 的支持不是很强。

最佳答案

My idea is to define the current time as a variable (before the video starts playing) and use it when pausing the video. However I just get "Uncaught ReferenceError: posterTime is not defined".

你的想法和代码很好,但你犯了一个基本错误。 记住:函数内部定义的变量仅在创建它的函数中存在。

使用 let 作为内部变量(如果可能),使用 var 作为全局变量。

解决方案:将变量定义为全局(在任何函数之外)...

const videos = document.querySelectorAll("video");
var posterTime = -1; //# global var, with starting value...
 
videos.forEach(video => {

    video.addEventListener("mouseover", function () 
    {
        posterTime = this.currentTime; //# set time
        this.currentTime = 0;
        this.play()
    })

    video.addEventListener("mouseout", function () 
    {
        this.currentTime = posterTime; //# get time
        this.pause();
    })
})

关于javascript - 使用 'this.currentTime' 获取视频的时间并将其重置为 'hover out' 上的起点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70433228/

相关文章:

javascript - 获取outerHTML代码问题

javascript - 如何修复 : Cannot read property 'GoogleAuthProvider' of undefined

javascript - 如何在 React 中显示图像,这些图像作为文件下载并保存在服务器上的文件夹中,文件路径存储在我的数据库中?

c# - 无论如何在 ajax 调用中从 asp.net-mvc 中的服务器端异常返回原始文本而不是 html?

jQuery:从较低级别的链接选择上一级的链接

android - 使用 MediaCodec 编码时,三分之二的屏幕为绿色

MATLAB getframe 捕获屏幕上的任何内容

css - 定位 html5 视频元素以适应自定义图形

javascript - 如何在jquery中右键单击添加dbclick()

javascript - 子文档组未获取正确的值