根据当前页面动态更改链接的CSS

Moc*_*k26 1 javascript jquery

我的网页顶部有以下链接:

 <ul class="icyLink">

      <li><a class="nav1" href="index.html">The World of Icengale</a></li>
      <li><a class="nav1" href="history.htm">History of Icengale</a></li>
      <li><a class="nav1" href="calendar.htm">Time & Calendar of Icengale</a></li>

 </ul>
Run Code Online (Sandbox Code Playgroud)

每个链接的颜色为蓝色,每个<li>都有背景图像(background-image:url('../ images/blue2.jpg').

我想要做的是根据当前页面动态更改单个链接的CSS.例如,如果有人在history.htm页面上,则链接的颜色将变为白色,背景图像将更改为另一个(在本例中为"blue3").所有其他链接的css将保留为同样的.我该怎么做?

一如既往,非常感谢任何和所有的帮助!

保重,祝大家愉快....

乔,约翰.

Dav*_*ing 7

您可以检查每个链接,看它是否与当前位置匹配.根据您的需要,这可以或多或少地提前,但是类似于:

var loc = window.location.pathname;

$('.icyLink').find('a').each(function() {
  $(this).toggleClass('active', $(this).attr('href') == loc);
});
Run Code Online (Sandbox Code Playgroud)

然后在CSS中设置活动类的样式:

.icyLink a.active{color:#fff}
Run Code Online (Sandbox Code Playgroud)