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

使用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>

CSS:

li a{
    color:#A60500;}li a:hover{
    color:#640200;
    background-color:#000000;}


暮色呼如
浏览 1065回答 3
3回答

森林海

使用jQuery,您可以使用该.each函数使用以下代码迭代链接:$(document).ready(function()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;$("[href]").each(function()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(this.href&nbsp;==&nbsp;window.location.href)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$(this).addClass("active"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;});});根据您的页面结构和使用的链接,您可能需要缩小选择范围,例如:$("nav&nbsp;[href]").each&nbsp;...如果您使用的是URL参数,则可能需要删除以下内容:if&nbsp;(this.href.split("?")[0]&nbsp;==&nbsp;window.location.href.split("?")[0])&nbsp;...这样您就不必编辑每个页面。

猛跑小猪

可以实现这一点,而无需单独修改每个页面(将“当前”类添加到特定链接),但仍然没有JS或服务器端脚本。这使用:target伪选择器,它依赖于#someid出现在地址栏中。<!DOCTYPE><html><head> &nbsp;&nbsp;&nbsp;&nbsp;<title>Some&nbsp;Title</title><style>:target&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;background-color:&nbsp;yellow;}</style></head><body><ul> &nbsp;&nbsp;&nbsp;&nbsp;<li><a&nbsp;id="news"&nbsp;href="news.html#news">News</a></li> &nbsp;&nbsp;&nbsp;&nbsp;<li><a&nbsp;id="games"&nbsp;href="games.html#games">Games</a></li> &nbsp;&nbsp;&nbsp;&nbsp;<li><a&nbsp;id="science"&nbsp;href="science.html#science">Science</a></li></ul><h1>Stuff&nbsp;about&nbsp;science</h1><p>lorem&nbsp;ipsum&nbsp;blah&nbsp;blah</p></body></html>有几个限制:如果页面未导航到使用其中一个链接,则不会着色;ID需要出现在页面顶部,否则页面会在访问时跳过一点。只要这些页面的任何链接都包含id,并且导航栏位于顶部,就不会有问题。其他页内链接(书签)也会导致颜色丢失。
打开App,查看更多内容
随时随地看视频慕课网APP