早年網頁視頻播放非 Flash 莫屬,但隨著行動裝置普及與 HTML5 標準成熟,<video> 元素已成為主流。原生播放器無需外掛、跨平台一致、可深度定製 UI,是現代 Web 開發的必備技能。


| 模組 | 對應 API / 邏輯 |
|---|---|
| 播放/暫停 | video.play() / pause()、切換按鈕樣式 |
| 進度條拖曳 | video.currentTime = 比例 * duration、timeupdate 同步 UI |
| 音量控制 | video.volume (0-1)、靜音切換、音量條拖曳 |
| 全螢幕 | 標準 requestFullscreen + 廠商前綴、fullscreenchange 監聽退出 |
| 時間顯示 | loadedmetadata 取總長、timeupdate 更新當前時間、格式化 mm:ss |
| 緩衝顯示 | video.buffered 區間、定時器更新緩衝條寬度 |
| 控制列自動隱藏 | 全螢幕下 mousemove 重置計時器、5 秒無操作淡出 |
function formatTime(seconds) {
seconds = Math.round(seconds);
var minutes = Math.floor(seconds / 60);
seconds = Math.floor(seconds % 60);
return (minutes >= 10 ? minutes : '0' + minutes) + ':' +
(seconds >= 10 ? seconds : '0' + seconds);
}
avalon.bind($('video_bar'), 'click', function(e) {
var ratio = (e.clientX - $('video_bar').offsetLeft) / $('video_bar').offsetWidth;
$('html5_video').currentTime = ratio.toFixed(2) * $('html5_video').duration;
});
function toggle_fullscreen() {
$('html5_video').className = 'video_fs';
fs = true;
$('video_control').className = 'fullscreen';
var elem = $('html5_video');
if (elem.msRequestFullscreen) elem.msRequestFullscreen();
else if (elem.mozRequestFullScreen) elem.mozRequestFullScreen();
else if (elem.webkitRequestFullscreen) elem.webkitRequestFullscreen();
}
function exit_fullscreen() {
$('html5_video').className = '';
fs = false;
active = false;
$('video_control').className = '';
if (document.exitFullscreen) document.exitFullscreen();
else if (document.webkitCancelFullScreen) document.webkitCancelFullScreen();
else if (document.mozCancelFullScreen) document.mozCancelFullScreen();
}
// 監聽瀏覽器原生退出全螢幕(Esc 鍵、UI 按鈕)
document.onmozfullscreenchange = document.onwebkitfullscreenchange = function() {
if ($('html5_video').clientWidth !== document.documentElement.clientWidth) {
exit_fullscreen();
}
};
function updateBuffered() {
var v = $('html5_video'), r = v.buffered;
if (r && r.length) {
var end = r.end(r.length - 1); // 取最後一段緩衝結束點
$('video_buffer_bar').style.width = (end / v.duration * 100) + '%';
}
}
setInterval(updateBuffered, 500);
<video id="html5_video" src="video.mp4"></video>
<div id="video_control">
<button id="control_btn" class="html5_video_play_btn"></button>
<div id="video_bar"><div id="video_progress_bar"></div></div>
<span id="html5_play_time">00:00</span> / <span id="html5_video_duration">00:00</span>
<div id="vol_bar"><div id="vol_value"></div></div>
<button id="mute_icon" class="html5_video_mute"></button>
<button id="html5_video_fullscreen"></button>
</div>
play(),或加 muted 屬性配合 playsinline:fullscreen 偽類支援度不一,建議用 JS 切換 class 控制video.requestPictureInPicture()video.playbackRate = 1.5<track kind="subtitles"> + WebVTTcanvas.drawImage(video) + MediaRecorder APIHTML5 原生 <video> API 功能完整,配合模組化的 UI 邏輯,即可打造媲美商業播放器的體驗。本文示範的代碼結構清晰、無外部依賴,適合作為專案播放器的基礎骨架再行擴展。