HTML5 视频:需要查找从 "play" 到 "pause" 和 javascript 的观看时间
HTML5 video: need to find viewed time from "play" to "pause" with javascript
我需要找到一个 HTML 视频从用户点击“播放”到点击“暂停”的观看时间;目前我只找到带有这样代码的 currentTime,但这不是我需要的:
$("video").on('timeupdate', function(){
console.log(this.currentTime);
});
- 在视频中
"play"
将 Date.now()
ms 值存储到元素 data-start
属性中
- 在视频中
"pause"
计算 Date.now()
和 data-start
的差异
- 将累积的 ms 结果存储到
data-viewtime
属性中,供以后参考和添加。
const EL_video = document.querySelector("#vid");
EL_video.addEventListener("play", () => {
EL_video.dataset.start = Date.now();
});
EL_video.addEventListener("pause", () => {
const diff = Date.now() - EL_video.dataset.start;
EL_video.dataset.viewtime = (+EL_video.dataset.viewtime || 0) + diff;
console.log(`Total view time: ${EL_video.dataset.viewtime} ms`);
});
video {max-height: 150px;}
<video id="vid" src="https://raw.githubusercontent.com/Ahmetaksungur/aksvideoplayer/main/videos/video-360.mp4" controls></video>
我需要找到一个 HTML 视频从用户点击“播放”到点击“暂停”的观看时间;目前我只找到带有这样代码的 currentTime,但这不是我需要的:
$("video").on('timeupdate', function(){
console.log(this.currentTime);
});
- 在视频中
"play"
将Date.now()
ms 值存储到元素data-start
属性中 - 在视频中
"pause"
计算Date.now()
和data-start
的差异
- 将累积的 ms 结果存储到
data-viewtime
属性中,供以后参考和添加。
const EL_video = document.querySelector("#vid");
EL_video.addEventListener("play", () => {
EL_video.dataset.start = Date.now();
});
EL_video.addEventListener("pause", () => {
const diff = Date.now() - EL_video.dataset.start;
EL_video.dataset.viewtime = (+EL_video.dataset.viewtime || 0) + diff;
console.log(`Total view time: ${EL_video.dataset.viewtime} ms`);
});
video {max-height: 150px;}
<video id="vid" src="https://raw.githubusercontent.com/Ahmetaksungur/aksvideoplayer/main/videos/video-360.mp4" controls></video>