如何让11ty识别页内链接为当前页面,实现导航激活状态?
解决11ty博客锚点导航激活状态问题
问题原因
11ty的page.url仅包含页面的路径部分(比如首页的page.url为/),不包含URL中的哈希(#后内容)——哈希是客户端侧的信息,服务端渲染时无法获取,所以你之前用{% if page.url == "/#about" %}的判断逻辑永远不会成立。
解决方案
方法一:前端JavaScript处理(推荐,适配锚点跳转+滚动激活)
通过监听页面加载、哈希变化和滚动事件,动态给对应导航链接添加激活类:
// 设置导航激活状态的函数 function updateActiveNav() { // 获取当前哈希(去掉#) let currentHash = window.location.hash.slice(1); // 处理滚动时的区块匹配(如果需要滚动到区块也激活对应链接) if (!currentHash) { const sections = document.querySelectorAll('section[id]'); sections.forEach(section => { const sectionTop = section.offsetTop - 100; // 可调整偏移量 const sectionBottom = sectionTop + section.clientHeight; if (window.scrollY >= sectionTop && window.scrollY < sectionBottom) { currentHash = section.id; } }); } // 移除所有链接的激活类 document.querySelectorAll('nav a').forEach(link => { link.classList.remove('underline'); }); // 给对应链接添加激活类 if (currentHash) { const targetLink = document.querySelector(`nav a[href$="#${currentHash}"]`); if (targetLink) targetLink.classList.add('underline'); } else { // 无哈希时默认激活首页/hero链接 const homeLink = document.querySelector('nav a[href="/"]'); if (homeLink) homeLink.classList.add('underline'); } } // 绑定事件触发更新 window.addEventListener('load', updateActiveNav); window.addEventListener('hashchange', updateActiveNav); window.addEventListener('scroll', updateActiveNav);
方法二:模板标记+简化JS
先在11ty模板中给导航链接添加标识属性,再通过JS匹配:
模板代码:
<!-- 导航链接添加data-section属性 --> <a href="/#about" data-section="about">About</a> <a href="/#contact" data-section="contact">Contact</a> <a href="/" data-section="hero-section">Home</a>
简化版JS:
function setActiveNav() { const currentSection = window.location.hash.slice(1) || 'hero-section'; document.querySelectorAll('nav a').forEach(link => { link.classList.toggle('underline', link.dataset.section === currentSection); }); } window.addEventListener('load', setActiveNav); window.addEventListener('hashchange', setActiveNav);
内容的提问来源于stack exchange,提问作者NicoleR
相关产品推荐
相关产品推荐

