它不干净,可能有更好的方法,但是:
HTML
<ul class="nav navbar-nav navbar-right">
<li id="navIndex" class=""><a href="index.html">Home</a></li>
<li id="navAbout" class=""><a href="about.html">About</a></li>
</ul>
JS(某处)
// Map ids with html page names
var pages = {
navIndex: "index.html",
navAbout: "about.html"
};
// Iterate over map
for(var property in pages) {
// Check to make sure that the property we're iterating on is one we defined
if(pages.hasOwnProperty(property)) {
// indexOf will be 0+ if it appears in the string
if(window.location.href.indexOf(pages[i]) > -1) {
// we can use property because we defined the map to be same as ids
// From https://stackoverflow.com/questions/2739667/add-another-class-to-a-div-with-javascript
var el = document.getElementById(property);
el.className += el.className ? ' active' : 'active';
break; // no need to keep iterating, we're done!
}
}
}
这或多或少是一种“肮脏”的方法,因为它需要的不仅仅是 JavaScript 才能工作(see Nick's answer 用于更简洁的实现)。
首先我们在 <li> 元素上设置标识符,然后我们将这些标识符与它们各自的 href 属性映射出来。
一旦我们映射出<li>s,我们就会遍历映射的键(我们将其设置为<li>s 上的id 属性)并检查href 属性是否存在于其中该站点的window.location.href,如果是:添加active 类并停止搜索,否则我们继续运输。