闽公网安备 35020302035485号
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>堆代码 duidaima.com</title>
</head>
<body>
<!-- 视频容器 -->
<video id="video_content1" width="640" height="360" controls>
<!-- 视频源 -->
<source src="your_video_source.mp4" type="video/mp4" />
</video>
<!-- 包含JavaScript代码 -->
<script src="your_script.js"></script>
</body>
</html>
2. JavaScript实现// 获取视频元素
let videoMat = "your_video_source.mp4";
let source = document.createElement('source');
let video = document.getElementById('video_content1');
// 设置视频源
source.src = videoMat;
source.type = 'video/mp4';
// 将源附加到视频元素
if (video) {
video.appendChild(source);
// 初始化变量
let startTime = null;
let lastUpdateTime = null;
let totalElapsedTime = 0;
// 'play'事件监听器
video.addEventListener('play', function () {
startTime = new Date();
lastUpdateTime = startTime;
console.log('视频正在播放。开始时间:', startTime);
});
// 'timeupdate'事件监听器
video.addEventListener('timeupdate', function () {
if (!video.paused && startTime !== null) {
const currentTime = new Date();
const elapsedSinceLastUpdate = (currentTime - lastUpdateTime) / 1000;
totalElapsedTime += elapsedSinceLastUpdate;
lastUpdateTime = currentTime;
console.log("从开始到现在的观看时间: " + totalElapsedTime + " 秒");
}
});
// 'pause'事件监听器
video.addEventListener('pause', function () {
// 仅当视频已在播放时存储暂停时间
if (startTime !== null) {
const pausedTime = video.currentTime;
console.log('视频已暂停。暂停时刻:', pausedTime);
checkAndUpdateItem(totalElapsedTime, 1, 'your_video_title');
}
});
// 'ended'事件监听器
video.addEventListener('ended', function () {
// 视频播放已结束
checkAndUpdateItem(totalElapsedTime, 1, 'your_video_title');
});
// 堆代码 duidaima.com
// 'play'事件监听器(从暂停时间继续播放)
video.addEventListener('play', function () {
// 如果视频之前暂停,继续从暂停时刻播放
if (startTime !== null) {
video.currentTime = video.currentTime;
}
});
}
解释HTML结构:我们使用<video>标签嵌入视频,并提供一个唯一标识符(video_content1)以便在JavaScript中访问。我们在body末尾包含JavaScript文件,以确保DOM加载完成后再运行脚本。
JavaScript实现:6.‘ended’事件表示视频播放结束。