You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript代码实现视频隐藏后自动停止播放?

Stop Video Playback When Hiding the Video Element

Hey there! This is an easy fix—you just need to add a simple line to your existing display function to pause the video when you hide it. Here's how to adjust your code:

Modified JavaScript Code

function display(id) {
  var vid = document.getElementById(id);
  if (vid.style.display === 'block') {
    vid.style.display = 'none';
    vid.pause(); // Stops the video playback immediately
    // Optional: Reset video to start if you want it to begin fresh next time
    // vid.currentTime = 0;
  } else {
    vid.style.display = 'block';
    // Optional: Auto-play when showing (note: browser policies may require user interaction, which your onclick already provides)
    // vid.play().catch(err => console.log("Auto-play blocked:", err));
  }
}

Quick Explanation

  • When you set the video's display to none, calling vid.pause() ensures the video stops playing entirely—even hidden videos will continue running in the background (including audio) if you don't explicitly pause them.
  • The optional vid.currentTime = 0 line resets the video to its starting point, which is handy if you want users to start from the beginning each time they show the video again.
  • If you want the video to auto-play when it becomes visible, uncomment the vid.play() line. Since your trigger is a user-initiated click, it should bypass most browser auto-play restrictions.

Your existing HTML doesn't need any changes—this tweak works seamlessly with what you already have!

内容的提问来源于stack exchange,提问作者user

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:04:46