3

我有一个 div,其中包含一个 UL 元素以及我的每个页面的目录。

目前,我不得不在活动元素(class="active")上硬编码一个特殊的类。但是,我正在尝试通过将 href 与浏览器的当前 URL 匹配来查看是否可以使用 CSS3 来完成这项工作。

例如,如果 toc div 的锚点中的 href 与页面的当前 URL 匹配,则为其添加特殊格式。

示例网址: http: //mysite.com/page-title/2

标记:

<div class="toc">
    <h3>Table of Contents</h3>
    <ul>
        <li><a href="http://mysite.com/page-title/">Part 1</a></li>
        <li><a href="http://mysite.com/page-title/2">Part 2</a></li>
        <li><a href="http://mysite.com/page-title/3">Part 3</a></li>
    </ul>
</div>

在上面的示例中,我想对第二个列表项元素应用特殊的 css 格式,因为它的 HREF 模式与 URL 模式匹配“/2”。

如果这不能通过 CSS 实现,如果您可以提供 jQuery 代码,我可以将它放在我的 jQuery 脚本中。

4

2 回答 2

6

使用 jQuery 类似下面的东西应该可以工作;

var urlString = window.location; // or try window.location.pathname

$('a[href="' + urlString + '"]').addClass("active");
于 2012-12-22T21:45:53.283 回答
1

这里不需要 JavaScript。只需将一个类添加到与当前页面对应的 body 标记,然后将相同的类添加到导航项。然后为匹配的集合创建一个 css 规则,如下所示:

<body class="products">
<div class="toc">
    <h3>Table of Contents</h3>
    <ul>
        <li><a href="http://mysite.com/page-title/" class="products-nav">Product Overview</a></li>
        <li><a href="http://mysite.com/page-title/2" class="home-nav">A More Dynamic Home Page</a></li>
        <li><a href="http://mysite.com/page-title/3" class="images-nav">Featured Images on Steroids</a></li>
    </ul>
</div>

<body class="home">
<div class="toc">
    <h3>Table of Contents</h3>
    <ul>
        <li><a href="http://mysite.com/page-title/" class="products-nav">Product Overview</a></li>
        <li><a href="http://mysite.com/page-title/2" class="home-nav">A More Dynamic Home Page</a></li>
        <li><a href="http://mysite.com/page-title/3" class="images-nav">Featured Images on Steroids</a></li>
    </ul>
</div>

等等然后:

.products .products-nav, .home .home-nav, .images .images-nav {
    font-weight: bold;
}
于 2012-12-22T21:49:13.220 回答