WordPress主题中Bootstrap Scrollspy类导致导航栏外部链接失效的技术咨询
Hey there! I see exactly what's going on—your navbar links work perfectly for smooth scrolling to internal anchors when the navbar-op class is active, but external page links stop working. Remove the class, and external links work again, but you lose that nice smooth scroll effect. Let's fix this by tweaking your jQuery code to tell the difference between internal anchor links and other links.
The Root Issue
Your current jQuery code runs event.preventDefault() on every matching link, which blocks external links from navigating to their target pages. We need to add a quick check to only apply the smooth scroll logic to internal anchor links, and let all other links behave normally.
Modified jQuery Code
Here's the updated scrollspy function that handles both cases seamlessly:
/* -------------------------------------------------------- ANIMATED SCROLL PAGE WITH ACTIVE MENU - BOOTSTRAP SCROLLSPY ----------------------------------------------------------- */ jQuery(function(){ "use strict"; jQuery(".navbar-op ul li a, .navbar-op a.navbar-brand, .intro-direction a, a.go-to-top").on('click', function(event) { var targetUrl = new URL(this.href); var currentUrl = new URL(window.location.href); // Only run smooth scroll for internal anchor links if (targetUrl.host === currentUrl.host && this.hash) { event.preventDefault(); var hash = this.hash; jQuery('html, body').animate({ scrollTop: jQuery(hash).offset().top }, 900, function(){ window.location.hash = hash; }); } // For external links or internal page links (no hash), let the browser handle navigation naturally }); });
How This Works
- We use the
URLAPI to compare the clicked link's domain with the current page's domain. - Internal Anchor Links: If the link is on the same domain and includes a hash (like
#page-top), we prevent the default action and run the smooth scroll animation. - All Other Links: External links (different domain) or internal page links (same domain but no hash, like your Projects/Blog pages) will bypass the smooth scroll code and navigate normally—no more broken jumps.
Quick Fix to Your nav.php
Wait, looking at your nav code, I noticed the <nav> tag doesn't have the navbar-op class yet! Add it so the jQuery selector can target the right elements:
<nav class="navbar navbar-pasific navbar-mp megamenu navbar-fixed-top navbar-op">
Test It Out
After making these changes:
- Click links like
Home (#page-top)orServices (#service): They should smoothly scroll to the target section. - Click links like
ProjectsorBlog: They should navigate to the correct page just like they're supposed to.
内容的提问来源于stack exchange,提问作者Mode Martínez Palenzuela

