首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

HTML5 視頻背景播放結束後切換為靜態圖片或定格最後一幀

     編輯:程式設計疑難解答

需求

用 `

方案一:監聽 ended 事件,切換背景圖並移除 video

<video id="bgVideo" autoplay muted style="width:100%; height:100%; object-fit:cover; position:fixed; top:0; left:0; z-index:-1;">
    <source src="bg.mp4" type="video/mp4">
</video>

<script>
const video = document.getElementById('bgVideo');
video.addEventListener('ended', () => {
    // 1. 設置 body 背景圖
    document.body.style.backgroundImage = "url('bg-end.jpg')";
    document.body.style.backgroundSize = "cover";
    document.body.style.backgroundPosition = "center";
    // 2. 移除或隱藏 video 元素
    video.remove(); // 或 video.style.display = 'none';
});
</script>

方案二:CSS 定格最後一幀(無需 JS)

<video id="bgVideo" autoplay muted playsinline 
    style="width:100%; height:100%; object-fit:cover; position:fixed; top:0; left:0; z-index:-1;"
    poster="bg-end.jpg">  
    <source src="bg.mp4" type="video/mp4">
</video>

關鍵屬性:

  • `poster`:視頻未播放或播放結束時顯示的圖片(需瀏覽器支援)。
  • `playsinline`:防止 iOS 全屏播放,保持在頁面內。

方案三:JS 定格最後一幀(不切換圖片)

video.addEventListener('ended', () => {
    video.currentTime = video.duration; // 跳到最後
    video.pause(); // 暫停在最後一幀
    // 可選:video.style.opacity = 1; 確保可見
});

注意事項

  • 視頻檔案較大時,建議預載或使用較小解析度。
  • 移動端自動播放策略:需 `muted` + `playsinline` 且用戶有交互才能自動播放。
  • 無障礙:提供 `prefers-reduced-motion` 媒體查詢停用動畫。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved