如何根据当前url获取jQuery或Javascript更改css?

我的导航区域与我的内容在一个单独的文件中,我使用php include将两者结合在一起。 我希望导航区域链接根据活动的页面(即当前URL)更改颜色。 所以我希望jQuery或Javascript读取当前的URL(实际上只是文件名,如home.html),然后根据它编写CSS。

所以,如果url = home.html,则为nav.home.background-> blue的change-css

在你的情况下,你可以尝试这样的事情:

$("A").each(function () { if (this.href == document.URL) { $(this).addClass('active'); } }); 

如果href属性与当前文档URL匹配,则检查每个链接,如果它确实将类“active”添加到元素CSS类。

一个小警告:这只有在菜单中引用并在实际文档中使用的绝对URL完全匹配时才有效。 因此,假设当前url为http://example.orghttps://stackoverflow.com/dir/ ,则不会突出显示,因为它已解析为http://example.orghttps://stackoverflow.com/dir/https://stackoverflow.com/questions/7572767/how-can-i-get-jquery-or-javascript-to-change-css-based-on-the-current-url/index.html将匹配。
(确保整个站点的每个页面都使用相同的URL,无论如何都是很好的做法,例如搜索引擎优化和缓存代理)

使用的不同部分是:

  • $("A")选择所有A元素(锚点)。 您可能希望通过选择菜单中的所有A元素来使其更具体一些,例如$("#menu A") 。 [jQuery的]
  • .each(func)对每个选定的元素执行指定的函数。 在该函数中, this将引用所选元素。 [jQuery的]
  • this.href返回链接资源的绝对URI ,而不是像您预期的那样返回HTML中指定的可能相对位置。 [标准DOM]
  • $(this).addClass(clzName)用于将CSS类添加到指定的元素。 [jQuery的]

要确保$("A")找到所有元素,请在文档完全加载后(在$(document).ready() jQuery事件处理程序中或使用BODY标记的onload属性)执行它。

我认为更好的解决方案是在html标记上设置一个类,而不是每页交换一个css文件。

 $("html").addClass(window.location.path.split(".")[0]); 

然后有任何基于该类的自定义CSS样式:

 html.home > .nav { background-color: blue; } html.about > .nav { background-color: green; } html.contact > .nav { background-color: red; } 

这只适用于每个页面都有分割扩展名的情况,即


既然您正在使用PHP,那么您可以在没有jQuery的情况下执行此操作:

  

或类似的东西,我对PHP知之甚少,但我确信它会是类似的东西,或者是基于它的

 var url_arr = document.URL.split('/'), page = url_arr[url_arr.length - 1]; switch (page) { case 'home.html': $('your-element').addClass('your-class'); break; /* other cases here */ } 

这应该够了吧。

要在javascript中阅读当前url:

 var url = window.location.href; 

要更改给定元素的css属性:

 $('some_selector').css({ backgroundColor, 'blue' }); 

像这样的东西

 var url = $(location).attr('href'); //get the url if(url.indexOf('home.html') != -1){ //indeOf returns -1 if item not found in string //so if it is not -1 (that is, found) //then apply the styles $('#nav').css('background','blue'); } 

但是,您可能需要一个switch或case语句来处理所有URL /部分。

就像是

 var url = $(location).attr('href'); var fileName = url.slice(url.lastIndexOf('/') + 1); switch (fileName){ case 'home.html': $('#nav').css('background','blue'); break; case 'about.html': $('#nav').css('background','red'); break; }