使用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;}
3 回答

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

猛跑小猪
TA贡献1858条经验 获得超8个赞
可以实现这一点,而无需单独修改每个页面(将“当前”类添加到特定链接),但仍然没有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>
有几个限制:
如果页面未导航到使用其中一个链接,则不会着色;
ID需要出现在页面顶部,否则页面会在访问时跳过一点。
只要这些页面的任何链接都包含id,并且导航栏位于顶部,就不会有问题。
其他页内链接(书签)也会导致颜色丢失。
添加回答
举报
0/150
提交
取消