如何通过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
displaytonone, callingvid.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 = 0line 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
相关产品推荐
相关产品推荐

