[英]how to add class 'active' to nav item whose href is in the location.pathname
我正在尝试在 Jekyll 模板之上构建一个博客风格的网站。 我目前正在编写和设计导航的样式,这给我带来了一些问题。 使用这个问题的答案,我设法在当前页面上添加了active
类,但这里有一些仍然需要解决的问题:
[baseurl]/reviews/[name-of-post]
,但评论“标签”未激活:我不确定如何解决第一个问题,但对于第二个问题,我想我需要在 location.pathname 中搜索相关的 href,但我需要进一步研究这个问题。 将根据需要进行更新,但我一直在玩这个,但没有运气,所以我想我会在此期间发布。
以下是相关部分的代码片段:
侧边导航 HTML(用 Liquid 编写)
<nav id="side-nav">
<ul class="nav-items-list">
<li id="nav-item"><a href="{{ site.baseurl }}/"><i class="fas fa-home"></i></a></li>
{% for page in site.pages %}
<li id="nav-item">
<a href="{{ site.baseurl }}/{{ page.title | downcase }}/">
<i class="{{ page.icon }}"></i>
</a>
</li>
{% endfor %}
</ul>
</nav>
示例页面(YAML frontmatter)
---
layout: page
title: Reviews
permalink: /reviews/
icon: "fas fa-star-half-alt"
---
jQuery
$(function(){
var current = location.pathname;
$('#nav-item a').each(function(){
var $this = $(this);
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
这应该足够了,但是如果需要更多代码,请告诉我。 所有代码也可在GitHub上找到,该项目也托管在 GitHub Pages 上。
提前致谢。
杰米
以下理论上应该有效:
// Compute the closest (2-part) base path from the current location
var basePath = '/' + window.location.pathname.split('/', 3).filter(Boolean).join('/') + '/';
// Add `active` class to the corresponding link if any
$('#nav-item a[href="' + basePath + '"]').addClass('active');
第一行基本上采用 pathName 的前两部分,因此:
/glossd/
,它会产生/glossd/
,/glossd/reviews/
,它会产生/glossd/reviews/
,/glossd/reviews/something/
,它仍然会产生/glossd/reviews/
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.