JavaScript点击事件跳转指定URL:视频关闭后跳转需求实现
Hey there! I see you're trying to get a button to play a video, then redirect users to another URL when they click to close the video. Let's tweak your existing code to make that happen—super straightforward once you know where to add the redirect logic.
First, let's break down what your current code does: it shows and plays the video when the #play button is clicked, then hides the video when you click on it. The missing piece is telling the browser to jump to your target URL right after hiding the video.
Here's the modified code with the redirect functionality added:
function playVideo() { $('#play').click(function() { var video = $('#final-video'); // Show and play the video video.css({ opacity: 1, pointerEvents: 'auto' }); video[0].play(); // Handle video click to hide and redirect video.click(function() { // Hide the video first $(this).css({ opacity: 0, pointerEvents: 'none' }); // Pause the video to stop background playback (good practice) this.pause(); // Redirect to your target URL in the same tab window.location.href = 'https://your-target-url.com'; // If you want to open the URL in a new tab instead, use this line: // window.open('https://your-target-url.com', '_blank'); }); }); }
Key tweaks I made:
- Added
this.pause(): This stops the video from playing in the background after it's hidden, which avoids confusing users with unexpected audio. - Added the redirect line:
window.location.href = 'your-url-here'sends users to your target URL in the same browser tab. If you prefer opening the URL in a new tab, swap that line withwindow.open('your-url-here', '_blank').
Just replace 'https://your-target-url.com' with the actual URL you want to redirect to, and you're all set!
内容的提问来源于stack exchange,提问作者emma 123456

