Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...