我很难将类 active 添加到包含站点当前页面的 li。网址 = http://polissagethibodeau.com/
这是相关的 HTML
<nav class="nav">
<ul class="sf-menu">
<li id="home">
<a href="./">Home</a>
</li>
<li>
<a href="./about.php">About us</a>
</li>
<li>
<a href="./services.php">Services</a>
<ul>
<li>
<a href="./services.php#passenger">Car, Truck and Vans</a>
</li>
<li>
<a href="./services.php#large">Semi, Boats, RV and Busses</a>
</li>
<li>
<a href="./services.php#air">Airplanes and Helicopters</a>
</li>
<li>
<a href="./services.php#polishing">Aluminum and Plexiglass polishing</a></li>
</ul>
</li>
<li>
<a href="./photo.php">Photos</a>
</li>
<li>
<a href="./contact.php">Contact Us</a>
</li>
</ul>
</nav>
我正在尝试应用 CSS
.sf-menu > li.active > a {
background: #c2e078;
}
这是我尝试使用但没有成功的脚本。
$(function() {
var path = window.location.pathname.substring(1);
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');
});
最佳答案
您可以通过两种或多种方式来完成。示例元素 来源LINK
1.----
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$("nav ul a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).addClass("active");
})
});
2.----
如果你想使用纯 javascript,这里是代码
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
window.onload = setActive;
3.----
function setActive() {
$('#nav').find('a').each(function () {
//console.log(document.location.href)
if (document.location.href == "http://......" + $(this).attr('href')) {
$(this).parents("ul").removeClass("hidden-ul");
$(this).parents().addClass("active");
}
});
}
window.onload = setActive;
关于javascript - 根据 url 将事件类添加到 nav li?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40413993/