我有一个视频库,我想在其中动态使用 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/