HTML5 视频播放器允许开发者嵌入视频内容到网页中。进度条是视频播放器的一个重要组成部分,它显示视频播放的当前位置以及总时长。工具提示(Tooltip)则是在用户将鼠标悬停在进度条上时,显示更详细的信息,如当前播放时间。
以下是一个简单的 HTML5 视频播放器进度条工具提示的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Player with Tooltip</title>
<style>
#video-container {
position: relative;
width: 640px;
height: 360px;
}
#progress-bar {
width: 100%;
height: 5px;
background-color: #ddd;
position: absolute;
bottom: 0;
}
#progress {
height: 100%;
background-color: #007bff;
}
#tooltip {
position: absolute;
background-color: rgba(0, 0, 0, 0.7);
color: white;
padding: 5px;
border-radius: 5px;
display: none;
}
</style>
</head>
<body>
<div id="video-container">
<video id="video" width="640" height="360" controls>
<source src="your-video-file.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<div id="progress-bar">
<div id="progress"></div>
</div>
<div id="tooltip"></div>
</div>
<script>
const video = document.getElementById('video');
const progressBar = document.getElementById('progress');
const tooltip = document.getElementById('tooltip');
video.addEventListener('timeupdate', () => {
const percent = (video.currentTime / video.duration) * 100;
progressBar.style.width = `${percent}%`;
});
progressBar.addEventListener('mousemove', (event) => {
const rect = progressBar.getBoundingClientRect();
const offsetX = event.clientX - rect.left;
const percent = offsetX / rect.width;
const time = percent * video.duration;
tooltip.textContent = formatTime(time);
tooltip.style.display = 'block';
tooltip.style.left = `${event.clientX}px`;
tooltip.style.top = `${rect.bottom + 20}px`;
});
progressBar.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
function formatTime(seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
</script>
</body>
</html>
mousemove
事件中的计算逻辑正确。video.currentTime
和 video.duration
是否正确获取。getBoundingClientRect()
获取进度条的位置信息。通过以上方法和示例代码,可以实现一个准确的 HTML5 视频播放器进度条工具提示。
领取专属 10元无门槛券
手把手带您无忧上云