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");
}
});
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…