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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9863396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:05:17  来源:igfitidea点击:

Dynamically change CSS of link based on current page

javascriptjquery

提问by Mock26

I have the following links at the top of my web page:

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

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

The color of each link is blue and each <li>has as a background image (background-image: url('../images/blue2.jpg').

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

What I would like to do is dynamically change the css of an individual link based on the current page. For example, if someone is on the history.htm page then the color of the link will change to white and the background image will change to another (in this case, "blue3). The css for all of the other links would remain the same. How would I do this?

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

As always, any and all help is greatly appreciated!

与往常一样,非常感谢任何和所有帮助!

Take care and have a great day....

保重,度过美好的一天......

ciao, john.

乔,约翰。

回答by David Hellsing

You can check each link and see if it matches the current location. This can be more or less advanced depending on your needs, but something like:

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

var loc = window.location.pathname;

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

Then style the active class in your CSS:

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

.icyLink a.active{color:#fff}

回答by xyz

You are looking for jQuery .cssor .addClassfunctions.

您正在寻找 jQuery.css.addClass函数。

回答by elclanrs

Set a unique body id in each page and an id on each menu item then:

在每个页面中设置一个唯一的 body id,在每个菜单项上设置一个 id,然后:

#home-page #home-menu,
#history-page #history-menu { background: blue; } // Etc....

回答by Wasim

<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>
<script>
$(document).ready(function(){
   $("a.nav1").click(function () {
      // switch all tabs off
      $(".active").removeClass("active");
      // switch this tab on
      $(this).addClass("active");
   });
});
</script>

css

css

.active{background-image: url('../images/blue3.jpg');color:#fff;}