我有一个关于向当前菜单项添加类的简单问题。
我有以下页面结构:
- index.jade
- about.jade
- articles/
- _data.json
- index.jade
- blog-post-1.jade
- blog-post-2.jade
- contact.jade
现在我创建了一个名为:.active
的类,它仅适用于根页面(index、about 和 contact ),但是当我单击 /articles
时,事件类并未添加到文章li
在菜单中。
我正在使用 Harp 网站上的代码片段:
ul
li(class="#{ current.source == 'index' ? 'active' : '' }")
a(href="/") Home
li(class="#{ current.source == 'about' ? 'active' : '' }")
a(href="/about") About
li(class="#{ current.source == 'articles' ? 'active' : '' }")
a(href="/articles") Articles
li(class="#{ current.source == 'contact' ? 'active' : '' }")
a(href="/contact") Contact
无论我尝试什么,我似乎都无法让 .active
菜单类在 /articles
上工作,也无法在任何文章页面:articles/blog-post-1
或 articles/blog-post-2
等。
还在 Harp 网站上我看到您可以添加:
{
path: ["articles", "hello-world"],
source: "hello-world"
}
但我不知道在哪里添加它。我将其添加到 articles/_data.json
文件中,但不起作用。
最佳答案
因此,您实际上不必添加当前源和当前路径,这是 Harp 在模板中提供的功能之一。您可以随时将其显示在页面上,如下所示:
pre: code= JSON.stringify(current, 0, 2)
假设您位于第一个博客文章页面,您会看到如下内容:
{
source: "blog-post-1"
path: [
"articles",
"blog-post-1"
]
}
因此,在这种情况下,您的导航不会被激活,因为 current.source
实际上不是 articles
,而是 blog-post-1
或 blog-post-2
。解决问题的最快方法是:
li(class="#{ current.path[0] === 'articles' ? 'active' : '' }")
a(href="/articles") Articles
这应该仍然适用于文章索引页面,其中 Harp 的 current
object看起来像:
{
source: "index"
path: [
"articles",
"index"
]
}
关于javascript - 将类添加到当前导航项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35742737/