開發視頻播放頁面時,ontimeupdate 用於即時獲取播放進度、觸發字幕切換、章節標記等互動。但直接賦值 video.ontimeupdate = fn 在 Chrome 可能失效,標準做法是使用 addEventListener。
// ❌ Chrome 下可能不觸發
video.ontimeupdate = function() { updateProgress(video.currentTime); };
// ✅ 所有現代瀏覽器通用
video.addEventListener('timeupdate', function() {
updateProgress(video.currentTime);
}, false);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Video 進度控制 Demo</title>
</head>
<body>
<video id="video" controls width="450" height="320"
poster="./images/poster.png"
src="./video/video.mp4"></video>
<div>時間: <span id="current">0</span> / <span id="duration">0</span> 秒</div>
<div>
<input type="number" id="seekInput" placeholder="跳轉秒數">
<button onclick="seekVideo()">跳轉</button>
</div>
<script>
const video = document.getElementById('video');
const curEl = document.getElementById('current');
const durEl = document.getElementById('duration');
video.addEventListener('loadedmetadata', () => {
durEl.textContent = video.duration.toFixed(1);
});
video.addEventListener('timeupdate', () => {
curEl.textContent = video.currentTime.toFixed(1);
});
function seekVideo() {
const t = parseFloat(document.getElementById('seekInput').value);
if (!isNaN(t)) video.currentTime = t;
}
</script>
</body>
</html>
ontimeupdate 屬性支援不完整removeEventListener) 管理生命週期| 事件 | 觸發時機 |
|---|---|
loadedmetadata | 元數據載入完成(可讀 duration) |
canplay | 可開始播放(緩衝足夠) |
playing | 播放開始/恢復 |
pause | 暫停 |
ended | 播放結束 |
seeking/seeked | 跳轉中/跳轉完成 |
error | 載入/播放錯誤 |
採用 addEventListener 統一綁定,構建穩健的視頻互動應用。