如何实现点击弹窗选项跳转后自动关闭HTML弹窗表单?
Got it, let's get this sorted! Right now, your popup stays open when you click the anchor links that jump to page sections—here's how to fix that so the popup closes automatically when those links are clicked:
Step 1: Add a shared class to your anchor links
First, give all the anchor links that should close the popup a common class (like popup-close-link). This lets us target all of them with one piece of JavaScript instead of repeating code for each link.
Step 2: Add JavaScript to handle the click event
Add a small script that listens for clicks on these links, closes the popup, and lets the normal anchor jump behavior work as expected.
Here's your modified code with these changes applied:
<html> <body> <!-- popup form start here --> <div id="popScroll"> <div class="popScroll"> <div class="popup"> <div id="option"> <div class="text"> <a href="#" class="popup-close-link"><img src="demo.png" alt=""></a><br> <a href="#" class="popup-close-link">Chemical</a> </div> <div class="text"> <a href="#logistics" class="popup-close-link"><img src="demo.png" alt="logistics"></a><br> <a href="#logistics" class="popup-close-link">logistics</a> </div> <div class="text"> <a href="#polymer" class="popup-close-link"><img src="demo.png" alt="polymer"></a> <a href="#polymer" class="popup-close-link">Polymer</a> </div> </div><br><br> <span onclick="document.getElementById('popScroll').style.display='none'" class="w3-button w3-display-topright" >Close</span> </div> </div> </div> <script> // Get all links with the popup-close-link class const popupLinks = document.querySelectorAll('.popup-close-link'); const popup = document.getElementById('popScroll'); // Add click event listener to each link popupLinks.forEach(link => { link.addEventListener('click', () => { // Close the popup popup.style.display = 'none'; }); }); </script> </body> </html>
How this works:
- When any link with the
popup-close-linkclass is clicked, the JavaScript triggers immediately to set the popup'sdisplaytonone, closing it. - The browser will still execute the default anchor link behavior (scrolling to the target section) right after closing the popup—so both actions happen seamlessly.
Alternative (if you prefer inline code):
If you don't want to use a shared class and JavaScript, you can add the close command directly to each link's onclick attribute, like this:
<a href="#logistics" onclick="document.getElementById('popScroll').style.display='none'">logistics</a>
This works too, but using the class-based method is cleaner and easier to maintain if you ever add more links to the popup.
内容的提问来源于stack exchange,提问作者Pranil

