假设我们的应用程序使用的是Safari的默认视频播放器。
当用户正在播放视频,然后试图使用搜索栏移动到视频的不同位置时,似乎首先触发pause
事件,然后我们将触发seeking
和seeked
事件。
我想知道我们是否可以在寻求之前获得currentTime
值。例如,假设用户使用搜索栏从t = 7
跳转到t = 42
,我想以某种方式获得7
作为currentTime
的值。
我希望我们可以通过访问pause
事件处理程序中的currentTime
属性来获得这个值,该事件处理程序在查找之后被调用,如下所示:
const video = document.querySelector('#myvideo');
video.addEventListener('pause', () => {
// I expected that the `video.currentTime` here has the "previous" position,
// but it already points to the new position
console.log(video.currentTime);
});
但不幸的是,currentValue
在那时已经更新为新值了。
有什么好的方法来实现它吗?
(编辑)手动缓存currentTime
没有帮助,因为显然timeupdate
事件在pause
事件之前触发。更具体地说,以下面的代码为例,当用户试图跳转到另一个位置时,cache
和currentTime
在pause
处理程序中打印似乎总是相同的。
<!DOCTYPE html>
<html>
<body>
<video
id="myvideo"
width="640"
height="360"
controls
src="video.mp4"
></video>
</body>
<script>
const video = document.querySelector("#myvideo");
let cache = 0;
video.addEventListener("timeupdate", () => {
cache = video.currentTime;
});
video.addEventListener("pause", () => {
console.log({ cache, currentTime: video.currentTime });
});
</script>
</html>
我想@Kaiido说"缓存两个值">就是这个意思。
代码未经测试(但看起来比保存在注释部分要好)
<script>
const video = document.querySelector("#myvideo");
let cache = 0;
let cache_prev = 0;
video.addEventListener("timeupdate", () => {
cache_prev = cache; //# save last known value
cache = video.currentTime; //# before updating to new currentTime
});
video.addEventListener("pause", () => {
console.log("cache_prev : " + cache_prev );
console.log("cache : " + cache );
console.log("currentTime : " + video.currentTime );
});
</script>