如何实现视频自动播放及播放完毕后自动跳转至其他页面?
Got it, let's walk through exactly how to set this up. Modern browsers have strict autoplay policies to prevent annoying unmuted videos from playing automatically, so we need to account for that first, then add the logic to redirect once the video finishes.
Step 1: Configure the Video Element for Auto-Play
Add a <video> tag with the necessary attributes to enable autoplay. Most browsers require the video to be muted for autoplay to work, so we'll include that along with autoplay and playsinline (for better mobile support):
Step 2: Add Auto-Redirect Logic
Attach an ended event listener to the video element. This event fires as soon as the video finishes playing, and we'll use it to trigger the redirect to your target page.
Here's the complete modified code snippet incorporating your existing HTML structure:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>eve_</title> <!-- Your existing link tags here --> </head> <body> <!-- Video element with autoplay setup --> <video id="autoPlayVideo" autoplay muted playsinline width="640" height="360"> <source src="your-video-file.mp4" type="video/mp4"> <!-- Fallback text if video isn't supported --> Your browser does not support the video tag. </video> <script> // Get the video element const video = document.getElementById('autoPlayVideo'); // Add event listener for when video ends video.addEventListener('ended', function() { // Redirect to your target page window.location.href = 'https://your-target-page-url.com'; }); </script> </body> </html>
Key Notes:
- Autoplay Policy Compliance: The
mutedattribute is critical here—most modern browsers (Chrome, Firefox, Safari) block autoplay of unmuted videos by default. If you need audio, you’ll have to let users interact with the page first (like a play button) to unmute, but that would break the fully automatic flow you want. - Video Source: Replace
your-video-file.mp4with the actual path to your video file. You can add additional<source>tags for other formats (like WebM) to support more browsers. - Redirect URL: Update
https://your-target-page-url.comto the URL of the page you want to redirect to.
That should do it—once the video finishes playing, the page will automatically redirect without any user interaction needed.
内容的提问来源于stack exchange,提问作者B.Ashcroft

