Shopify导航菜单高亮:首页链接全局高亮,仅PL Pro页切换
解决方案
方案一:使用Liquid原生代码(推荐)
直接在模板里通过Liquid判断当前页面状态,无需依赖前端JS,稳定性更高:
<span class="inline-menu"> {% for link in linklists[section.settings.menu].links %} {% assign is_current = false %} {% if link.url == '/' %} <!-- 首页链接:默认高亮,仅访问/pages/pl-pro时取消 --> {% unless request.path == '/pages/pl-pro' %} {% assign is_current = true %} {% endunless %} {% elsif link.url == '/pages/pl-pro' %} <!-- PL Pro链接:仅自身页面高亮 --> {% if request.path == link.url %} {% assign is_current = true %} {% endif %} {% endif %} <a class="inline-menu__link {% if is_current %}current{% endif %}" href="{{ link.url }}">{{ link.title }}</a> {% endfor %} </span>
逻辑说明
- 借助Shopify内置的
request.path变量获取当前页面的路径(不含域名) - 首页链接默认添加
current类,仅在访问/pages/pl-pro时移除 - PL Pro链接仅在当前页面匹配时添加
current类
方案二:JavaScript方案(备选)
如果需要用前端JS实现,调整逻辑为强制首页默认高亮,仅在PL Pro页面切换:
document.addEventListener('DOMContentLoaded', function() { const currentPath = window.location.pathname; const navLinks = document.querySelectorAll('.inline-menu__link'); navLinks.forEach(link => { link.classList.remove('current'); // 首页链接:默认高亮,当前是PL Pro页面除外 if (link.getAttribute('href') === '/' && currentPath !== '/pages/pl-pro') { link.classList.add('current'); } // PL Pro链接:仅自身页面高亮 if (link.getAttribute('href') === '/pages/pl-pro' && currentPath === '/pages/pl-pro') { link.classList.add('current'); } }); });
逻辑说明
- 页面加载完成后获取当前路径
- 先清除所有链接的
current类 - 给首页链接添加
current类(当前为PL Pro页面时跳过) - 给PL Pro链接添加
current类(仅当前页面匹配时)
内容的提问来源于stack exchange,提问作者powerdown
相关产品推荐
相关产品推荐

