HTML5 提供了對直接在網頁中嵌入和播放影片的原生支持,可以輕鬆整合多媒體內容,而無需依賴 Flash 等第三方插件。以下是在 HTML5 中使用影片的一些方法:

  1. 使用<video>元素: <video>元素是嵌入影片的 HTML5 核心功能。

    html
    <video width="640" height="360" controls> <source src="example.mp4" type="video/mp4"> Your browser does not support the video tag. </video>
    • widthheight :設定視訊播放器的寬度和高度。
    • controls :新增播放、暫停、音量等播放控制。
    • <source> : 指定多個source元素提供不同的影片格式,以獲得更好的瀏覽器相容性。
  2. 多種影片格式:最好包含多種影片格式,以確保不同瀏覽器之間的相容性。常見格式包括 MP4、WebM 和 Ogg。

    html
    <video width="640" height="360" controls> <source src="example.mp4" type="video/mp4"> <source src="example.webm" type="video/webm"> <source src="example.ogv" type="video/ogg"> Your browser does not support the video tag. </video>
  3. 後備內容:包含不支援<video>元素的瀏覽器的後備內容。

    html
    <video width="640" height="360" controls> <source src="example.mp4" type="video/mp4"> <source src="example.webm" type="video/webm"> <source src="example.ogv" type="video/ogg"> Your browser does not support the video tag. </video>
  4. 自動播放和循環:您可以使用autoplayloop屬性自動開始播放影片並循環播放。

    html
    <video width="640" height="360" controls autoplay loop> <source src="example.mp4" type="video/mp4"> Your browser does not support the video tag. </video>
  5. 海報圖像:新增在影片開始播放之前顯示的海報圖像。

    html
    <video width="640" height="360" controls poster="poster.jpg"> <source src="example.mp4" type="video/mp4"> Your browser does not support the video tag. </video>
  6. 響應式影片:使用基於百分比的寬度使您的影片具有響應式。

    html
    <div style="position: relative; padding-bottom: 56.25%; height: 0;"> <video style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" controls> <source src="example.mp4" type="video/mp4"> Your browser does not support the video tag. </video> </div>
  7. JavaScript 控制:使用 JavaScript 以程式方式控制影片播放。

    html
    <video id="myVideo" width="640" height="360" controls> <source src="example.mp4" type="video/mp4"> Your browser does not support the video tag. </video> <script> var video = document.getElementById("myVideo"); function playPause() { if (video.paused) video.play(); else video.pause(); } </script>

請記住檢查您想要使用的功能的瀏覽器相容性,並考慮提供替代內容或使用功能檢測和漸進增強技術以獲得更好的使用者體驗。