Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

css - JavaScript add class depending on current URL

For my website navigation I need to add the class 'active' to the li element depending on if it matches the current URL.

Nav HTML:

<ul id="nav">
    <div id="wrapper">
        <li><a href="/">Home</a></li>
        <li><a href="/tagged/Review">Reviews</a></li>
        <li><a href="/tagged/First_Look">First Looks</a></li>
        <li><a href="/tagged/Commentary">Commentaries</a></li>
        <li><a href="/tagged/Walkthrough">Walkthroughs</a></li>
        <li><a href="/tagged/Achievement">Achievements</a></li>
    </div>
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to use "pure" ("vanilla") JavaScript, use the following code(assuming that <ul id="nav"> exists):

window.onload = function() { 
    var all_links = document.getElementById("nav").getElementsByTagName("a"),
        i=0, len=all_links.length,
        full_path = location.href.split('#')[0]; //Ignore hashes?

    // Loop through each link.
    for(; i<len; i++) {
        if(all_links[i].href.split("#")[0] == full_path) {
            all_links[i].className += " active";
        }
    }
}

Using jQuery:

$(document).ready(function(){
    var full_path = location.href.split("#")[0];
    $("#nav a").each(function(){
        var $this = $(this);
        if($this.prop("href").split("#")[0] == full_path) {
            $this.addClass("active");
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...