[英]How to write this simple javascript or jquery?
我有一些像這樣的導航鏈接:
<ul id="nav">
<li><a href="index.html">Home</a>
<li><a href="about.html">About</a>
<li><a href="contact.html">Contact</a>
</ul>
如何將名為active
的CSS類添加到包含其值與當前url匹配的a href
的列表項的開始<li>
標記中?
例如,如果用戶所在的當前頁面是about.html
那么導航應如下所示:
<ul id="nav">
<li><a href="index.html">Home</a>
<li class="active"><a href="about.html">About</a>
<li><a href="contact.html">Contact</a>
</ul>
請注意:
網址可以有其他參數,如:
about.html?富=酒吧和酒吧= 1.00
因此,用於檢測網址的任何內容都不應考慮參數,而只考慮頁面名稱和擴展名。
我更喜歡在普通的JavaScipt中實現這一點,因為我沒有在網站上使用jQuery,但是其中一個很好。
當它從另一個頁面登陸時,索引頁面在url中有index.html,但如果域是類型,則顯示為:
http://www.sitename.com/
因此,如果未指定頁面,則應將活動類附加到主列表的標記。
jQuery的:
if(window.location.pathname === '') {
$('#nav li:first-child').addClass('active');
}
else {
var path = window.location.pathname;
path = path.substr(path.lastIndexOf('/') + 1);
$('#nav li').filter(function(index) {
return path === $(this).children('a').attr('href');
}).addClass('active');
}
普通的JavaScript:
var menu_elements = document.getElementById('nav').children;
if(window.location.pathname === '') {
menu_elements[0].className += ' active';
}
else {
var path = window.location.pathname;
path = path.substr(path.lastIndexOf('/') + 1);
for(var i = menu_elements.length; i--;) {
var element = menu_elements[i];
var a = element.children[0];
if(a.href === path) {
element.className += ' active';
break;
}
}
}
注意: FF 3.0不支持children[]
。 如果您遇到任何與children
問題,可以使用適當的getElementsByTagName
調用替換它。
簡單版
window.onload=function() {
var activeLi;
if (location.pathname) {
var fileName = location.pathname.substring(pathname.lastIndexof('/')+1);
/* just take the start -
not handling filenames that are substrings of other filenames
nor filenames with more than one dot. */
fileName = fileName.split('.')[0];
var links = document.getElementById('nav').getElementsByTagName('a');
for (var i=0;i<links.length;i++) {
if (links[i].href.indexOf(fileName)==0) { // starts with filename
activeLi = links[i].parentNode;
break;
}
}
}
else { // no page given
activeLi = document.getElementById('nav').getElementsByTagName('li')[0];
}
if (activeLi) activeLi.className="active";
}
更復雜的是將活動添加到className,但是如果你沒有在LI上有其他類,那么它就不需要 - 但是如果你使用jQuery則更簡單。
//Get sub-domain url
var currentUrl = window.location.href,
splitUrlArr = currentUrl.replace(/\?.*/,'').split('\/');
subDomainUrl = splitUrlArr[splitUrlArr.length-1];
//if url matches the site home url, add classname 'active' to first li
if(splitUrlArr.join('\/') == currentUrl) {
document.getElementById('nav').getElementsByTagName('li')[0].className = "active";
}else {
//Find the matching href and add className 'active' to its parent li
var targetLi = null;
var links = document.getElementById('nav').getElementsByTagName('a');
for (var i=0; i < links.length; i++) {
if (links[i].href === subDomainUrl) {
targetLi = links[i].parentNode;
break;
}
}
if(targetLi) { targetLi.className = "active"; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.