做自製播放器時,幾乎一定會用到 ontimeupdate——它會隨播放進度觸發,可以拿來更新進度條、切換章節、同步顯示字幕或額外資訊。但在某些環境下,這個事件會「怎麼掛都不動」,特別是在 Chrome 上。本文記錄一下問題現象與解法。
HTML5 的 Video 物件支援多種格式在線播放,並開放了完整的事件模型,可以用 JavaScript 控制播放行為。最直覺的寫法是在 onload 裡掛上事件:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>Video Event Demo</title>
</head>
<body>
<script type="text/javascript">
function timeUpdate() {
document.getElementById('time').innerHTML = video.currentTime;
}
function durationChange() {
document.getElementById('duration').innerHTML = video.duration;
}
function seekVideo() {
document.getElementById('video').currentTime =
document.getElementById('seekText').value;
}
window.onload = function () {
var videoPlayer = document.getElementById("video");
videoPlayer.ontimeupdate = function () { timeUpdate(); };
};
</script>
<div>
<video id="video" controls="controls"
poster="./images/videoground1.png"
src="./videoSource/video1.mp4" width="450px" height="320px"
ondurationchange="durationChange()" />
</div>
<div>Time: <span id="time">0</span> of <span id="duration">0</span> seconds.</div>
<div>
<input type="text" id="seekText" />
<input type="button" id="seekBtn" value="Seek Video" onclick="seekVideo();" />
</div>
</body>
</html>
除了上面的寫法,我們也很常動態掛事件:
video.ontimeupdate = function () { getCurrentVideoPosition(); };
問題是,這行在 Chrome 上有時不會觸發。原因大概是 ontimeupdate 屬於「事件處理器內容屬性」,在部分版本的原生元素上尚未完整實作,直接指派函式不會被註冊。
把它換成標準的事件監聽寫法就正常了:
videoPlayer.addEventListener("timeupdate", function () {
getCurrentVideoPosition();
}, false);
這個方法的好處不只是繞過 bug——它本身就是標準 API,同時相容 IE(9 以後)、Firefox、Chrome 與 Safari,而且同一個事件可以掛多個監聽器而不會互相覆蓋。所以在實務上,addEventListener 應該是首選寫法,而 onxxx 指派法只適合簡單場合。
做播放器時常一起用的還有:durationchange(總長度已知時觸發,適合初始化進度條)、timeupdate(約每 250 毫秒一次,更新播放位置)、seeking / seeked(拖動進度條的前後狀態)、play / pause(切換播放圖示)。把這些事件都掛上 addEventListener,播放器的狀態管理會清楚很多。