导航链接仅能在新标签页打开问题求助
导航外部链接无法跳转问题解决
问题描述
我已尝试为导航链接设置外部页面地址,但点击链接时无法直接跳转至目标页面,仅能通过新标签页打开。其中Tokenomics等锚点链接可正常滚动定位到页面对应位置,而Play to Earn、White Paper等需跳转至外部页面的链接无法正常工作。对接的开发人员沟通效率极低,特此求助。
相关HTML代码
<a href="#home" class="nav-link">Home</a> <a href="#playtoearn" class="nav-link">Play to Earn</a> <a href="#tokenomics" class="nav-link">Tokenomics</a> <a href="#whitepaper" class="nav-link">White Paper</a> <a href="#support" class="nav-link" style="display: inline;"><span class="support">Support</span></a>
补充app.js代码
const swiper = new Swiper(".swiper", { // If we need pagination pagination: { el: ".swiper-pagination", }, // autoplay: { // delay: 5000, // }, speed: 800, loop: true, // Navigation arrows navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, }); // Smooth scrolling $("nav a").on("click", function (e) { e.preventDefault(); const href = $(this).attr("href"); $("html, body").animate({ scrollTop: $(href).offset().top -100 }, 500); }); const header = document.querySelector('.header') let toggler = document.querySelector('.toggler'); toggler.onclick = ()=> { header.classList.add('navbar-bg') toggler.firstChild.classList.toggle("fa-times") toggler.firstChild.classList.toggle("fa-bars") } document.body.onscroll = () => { if (document.body.scrollTop == 0 && !toggler.firstChild.classList.contains('fa-times')) { header.classList.remove('navbar-bg') } else { header.classList.add('navbar-bg') } }
问题原因
核心问题出在平滑滚动的JS逻辑里:$("nav a").on("click", function (e) { e.preventDefault(); ... }) 对所有导航内的链接都执行了e.preventDefault(),直接阻止了浏览器的默认跳转行为。锚点链接能正常滚动是因为手动添加了滚动动画逻辑,但外部链接被阻止后没有对应的跳转处理,因此左键点击无效,只能通过右键新标签页打开。
修复方案
修改点击事件逻辑,仅对锚点链接(href以#开头且页面存在对应DOM元素)执行平滑滚动并阻止默认行为,外部链接交给浏览器正常处理:
// 修改后的平滑滚动逻辑 $("nav a").on("click", function (e) { const href = $(this).attr("href"); // 仅处理锚点链接(href以#开头且存在对应元素) if (href.startsWith("#") && $(href).length > 0) { e.preventDefault(); $("html, body").animate({ scrollTop: $(href).offset().top - 100 }, 500); } // 外部链接不做干预,保留浏览器默认跳转行为 });
同时注意:确保你已将外部链接的href修改为正确的外部地址,比如将
<a href="#playtoearn" class="nav-link">Play to Earn</a>
改为
<a href="https://你的外部页面地址" class="nav-link">Play to Earn</a>
内容的提问来源于stack exchange,提问作者gmdisnuts
相关产品推荐
相关产品推荐

