HTML5中video元素事件详解(实时监测当前播放时间)
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在HTML5中,<video>
元素支持一系列的事件,可以用来监测视频播放的各个阶段。其中,timeupdate
事件每次当媒体的播放位置发生改变时都会被触发。我们可以利用这个事件来实现实时监测当前播放时间的功能。
以下是一个简单的示例代码,展示如何使用timeupdate
事件来输出视频的当前播放时间:
<!DOCTYPE html>
<html>
<head>
<title>Video Time Update Example</title>
</head>
<body>
<video id="myVideo" width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<p id="current-time">Current time: 0:00</p>
<script>
// 获取video元素和用于显示当前播放时间的段落
var video = document.getElementById('myVideo');
var time = document.getElementById('current-time');
// 为video元素添加timeupdate事件监听器
video.addEventListener('timeupdate', function() {
// 更新当前播放时间
var currentMinutes = Math.floor(video.currentTime / 60);
var currentSeconds = Math.floor(video.currentTime % 60);
var formattedTime = currentMinutes + ":" + (currentSeconds < 10 ? '0' : '') + currentSeconds;
time.textContent = "Current time: " + formattedTime;
});
</script>
</body>
</html>
在这个例子中,我们首先获取了视频元素和用于显示当前播放时间的<p>
元素。然后,我们为视频元素添加了一个timeupdate
事件的监听器。每当事件触发时,监听器函数就会执行,计算当前播放时间,并将其格式化后显示在屏幕上。
评论已关闭