简体   繁体   中英

How can I get jQuery or Javascript to change css based on the current url?

I have a navigation area in a separate file from my content, and I pull together the two using a php include. I want the navigation area links to change color based on whatever page is active, ie the current URL. So I want jQuery or Javascript to read the current URL (actually just the filename, like home.html), then write CSS based on that.

So like, if url=home.html, change-css for nav.home.background-> blue

In your situation, you could try something like this:

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

That checks for every link if the href attribute matches the current documents URL, and if it does add class 'active' to the elements CSS classes.

A small caveat: this will only work if the absolute URL referred to in the menu and used in the actual document match exactly. So let's say the current URL is http://example.org/dir/ , then <a href="index.html"> will not be highlighted, since it resolves to http://example.org/dir/index.html . <a href="/dir/"> will match.
(Making sure the same URL is used for each page throughout the site is good practice anyway, eg for search engine optimization and caching proxies)

The different parts used are:

  • $("A") selects all A elements (anchors). You'll probably want to make it a bit more specific by selecting all A elements within your menu, eg $("#menu A") . [jQuery]
  • .each(func) executes the specified function on each of selected elements. Within that function this will refer to the selected element. [jQuery]
  • this.href returns the absolute URI of the linked resource , not, as you might expect, the possibly relative location specified in the HTML. [standard DOM]
  • $(this).addClass(clzName) is used to add a CSS-class to the specified element. [jQuery]

To make sure $("A") finds all elements, execute it after the document is fully loaded (in the $(document).ready() jQuery event-handler, or using the onload attribute of the BODY tag).

I think a much better solution would be to set a class on the html tag rather than swap out a css file per page.

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

and then have any custom css styles based off of that class:

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

This would only work if each page had an extension to split, that is


Since you're using PHP you could do this without jQuery at all:

<html class="<?php $_SERVER['PHP_SELF'] ?>">

or something like that, I know little about PHP but I'm sure it would be something similar or built off of this

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

}

That should do the trick.

Something like this

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');
}

You probably need a switch or case statement, though, to deal with all the URLs/sections.

Something like

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

To read the current url in javascript:

var url = window.location.href;

To change a css property on a given element:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM