Bootstrap 4下拉菜单:点击锚点无法跳转至指定href地址求助
Hey there! I see you've got a Bootstrap 4 dropdown menu working with hover-triggered expansion on desktop and click-triggered on mobile, but need the anchor links to properly navigate to their href targets in both views. Let's fix that up!
The Core Issue
By default, Bootstrap's dropdown component intercepts click events on menu items to manage the dropdown state, which can prevent your anchor links from firing their default navigation behavior. We need to adjust the event handling to let the links do their job while keeping the dropdown functionality intact.
Step-by-Step Solution
1. Preserve Desktop Hover Behavior (CSS)
First, keep your desktop hover expansion working with this media query CSS:
@media (min-width: 992px) { .dropdown:hover .dropdown-menu { display: block; } }
2. Tweak Dropdown Event Handling (JavaScript)
Use jQuery to adjust the dropdown's behavior so clicks on anchor links don't get blocked:
$(document).ready(function() { // Initialize the dropdown component $('.dropdown-toggle').dropdown(); // Function to adapt dropdown behavior based on screen size function setDropdownBehavior() { if ($(window).width() >= 992) { // On desktop: Disable click-triggered dropdown (rely solely on hover) $('.dropdown-toggle').off('click.bs.dropdown'); } else { // On mobile: Re-enable click-triggered dropdown functionality $('.dropdown-toggle').dropdown(); } } // Run setup on page load and window resize setDropdownBehavior(); $(window).resize(setDropdownBehavior); // Ensure anchor links navigate correctly $('.dropdown-menu a').on('click', function(e) { // Stop the click event from bubbling up to the dropdown parent (avoids state conflicts) e.stopPropagation(); // Optional: Close the dropdown on mobile after link click for better UX if ($(window).width() < 992) { $(this).closest('.dropdown').removeClass('show'); $(this).closest('.dropdown-menu').removeClass('show'); } }); });
How This Works
- Desktop View: We disable the default click trigger for dropdown toggles so hover remains the only way to expand the menu. When you click an anchor link,
e.stopPropagation()ensures the dropdown doesn't intercept the click, letting the browser navigate straight to thehreftarget. - Mobile View: The dropdown stays click-triggered for expansion. After tapping an anchor link, we optionally close the dropdown (for cleaner UX) and let the navigation proceed normally since we've stopped the event from interfering with the dropdown's state.
Testing the Fix
After applying these changes, test both views:
- On desktop, hover to expand the menu, then click any anchor link—it should navigate to the specified URL immediately.
- On mobile, tap the dropdown toggle to expand, then tap an anchor link—it should navigate and optionally close the dropdown menu.
内容的提问来源于stack exchange,提问作者Inderjeet

