使用CSS更改当前页面的链接颜色

Jos*_*ren 41 html javascript css

一个样式如何链接当前页面与其他页面不同?我想交换文字和背景的颜色.

HTML:

<ul id="navigation">
    <li class="a"><a href="/">Home</a></li>
    <li class="b"><a href="theatre.php">Theatre</a></li>
    <li class="c"><a href="programming.php">Programming</a></li> 
</ul>
Run Code Online (Sandbox Code Playgroud)

CSS:

li a{
    color:#A60500;
}

li a:hover{
    color:#640200;
    background-color:#000000;
}
Run Code Online (Sandbox Code Playgroud)

小智 69

使用jQuery,您可以使用该.each函数使用以下代码迭代链接:

$(document).ready(function() {
    $("[href]").each(function() {
        if (this.href == window.location.href) {
            $(this).addClass("active");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

根据您的页面结构和使用的链接,您可能需要缩小选择范围,例如:

$("nav [href]").each ...
Run Code Online (Sandbox Code Playgroud)

如果您使用的是URL参数,则可能需要删除以下内容:

if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...
Run Code Online (Sandbox Code Playgroud)

这样您就不必编辑每个页面.


N 1*_*1.1 47

a:active:当您单击链接并按住它时(激活!).
a:visited:当链接已被访问时.

如果您希望突出显示与当前页面对应的链接,则可以为链接定义一些特定样式 -

.currentLink {
   color: #640200;
   background-color: #000000;
}
Run Code Online (Sandbox Code Playgroud)

li在服务器端或客户端(使用JavaScript)将此新类添加到相应的(链接).


And*_*y G 9

可以实现这一点,而无需单独修改每个页面(将"当前"类添加到特定链接),但仍然没有JS或服务器端脚本.这使用:target伪选择器,它依赖于#someid出现在地址栏中.

<!DOCTYPE>
<html>
<head>
    <title>Some Title</title>
<style>
:target {
    background-color: yellow;
}
</style>
</head>
<body>
<ul>
    <li><a id="news" href="news.html#news">News</a></li>
    <li><a id="games" href="games.html#games">Games</a></li>
    <li><a id="science" href="science.html#science">Science</a></li>
</ul>
<h1>Stuff about science</h1>
<p>lorem ipsum blah blah</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

有几个限制:

  • 如果页面未导航到使用其中一个链接,则不会着色;
  • ID需要出现在页面顶部,否则页面会在访问时跳过一点.

只要这些页面的任何链接都包含id,并且导航栏位于顶部,就不会有问题.


其他页内链接(书签)也会导致颜色丢失.

  • +1 OP要求“使用CSS”,而不是像接受的答案那样的JavaScript。不过,id 必须是唯一的,因此我仍在努力寻找一种方法来定位内容部分及其相关链接(例如选项卡式菜单项)。 (2认同)

Gov*_*Rai 6

JavaScript 将完成这项工作。

获取文档中的所有链接并将它们的参考 URL 与文档的 URL 进行比较。如果匹配,则向该链接添加一个类。

JavaScript

<script>
    currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
    currentLinks.forE??ach(function(link) {
        link.className += ' current-link')
    });
</script>
Run Code Online (Sandbox Code Playgroud)

One Liner Version of Above

document.querySelectorAll('a[href="'+document.URL+'"]').forE??ach(function(elem){e??lem.className += ' current-link')});
Run Code Online (Sandbox Code Playgroud)

CSS

.current-link {
    color:#baada7;
}
Run Code Online (Sandbox Code Playgroud)

其他注意事项

上面 Taraman 的 jQuery 答案只搜索[href]哪些将返回link标签,而不是a依赖于href属性的标签。搜索a[href='*https://urlofcurrentpage.com*']仅捕获那些符合条件的链接,因此运行速度更快。

此外,如果您不需要依赖 jQuery 库,那么 vanilla JavaScript 解决方案绝对是您要走的路。

  • 当您可以使用更好的选择器时,您不应该使用如此广泛的选择器和循环结果。这个单行向当前链接添加类`document.querySelectorAll('a[href="'+document.URL+'"]').forEach(function(elem){elem.className += 'current-link')} );` (3认同)