這就是我的代碼的樣子:
<div class="header-nav navbar-collapse collapse ">
<ul id="navigation" class=" nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="about-us.html">About Us</a>
</li>
</ul>
</div>
當用戶在該特定頁面上但到目前為止沒有成功時,我一直在嘗試將活動類添加到它們中的每一個,這就是我的腳本的樣子:
var i = 0;
[].forEach.call(document.querySelectorAll('li > a'), function(nav) {
console.log(nav.pathname,window.location.pathname);
if (nav.pathname === window.location.pathname){
i = 1;
console.log(i);
nav.classList.add('active')
}
else{
console.log(i)
nav.classList.removeClass('active')
}
})
活動類設定在“a”而不是“li”上,我不知道如何解決這個問題。也許有人可以幫助我?
uj5u.com熱心網友回復:
在查看這些類時,您可能正在使用 Bootstrap。我將這些庫添加到片段中,并更新了一些類。我還在另一個導航項中添加了 href 等于,js因為那是片段視窗的路徑名。否則它不會添加活動類,因為不會有一個相等的路徑名。
我還將導航專案更改為藥丸,因此您可以更輕松地查看活動鏈接。
var i = 0;
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
console.log({
navPathname: nav.pathname,
windowLocationPathname: window.location.pathname,
areEqual: nav.pathname === window.location.pathname,
});
if (nav.pathname === window.location.pathname) {
nav.classList.add('active')
} else {
nav.classList.remove('active')
}
})
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div class="navbar navbar-light bg-light">
<ul id="navigation" class="nav nav-pills">
<li class="nav-item">
<a class="nav-link" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="js">JS</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about-us.html">About Us</a>
</li>
</ul>
</div>
uj5u.com熱心網友回復:
要定位父元素,您有幾個選項 - 我最喜歡的是element.closest(selector)它需要一個開始element并找到closest匹配的包含父元素selector
let els = document.querySelectorAll('li > a');
els.forEach(el => {
el.addEventListener('click', e => {
els.forEach(a => a.closest('li').classList.remove('active'));
e.target.closest('li').classList.add('active');
})
})
li.active {
background-color: green;
}
<ul>
<li><a href='#'>link 1</a></li>
<li><a href='#'>link 1</a></li>
<li><a href='#'>link 1</a></li>
</ul>
uj5u.com熱心網友回復:
感謝這一點,我將這兩個回應合并為一個對我有用的回應,這是一個腳本,它甚至不需要將類接觸到導航欄中:
document.querySelectorAll('ul.nav > li > a').forEach((nav) => {
console.log({
navPathname: nav.pathname,
windowLocationPathname: window.location.pathname,
areEqual: nav.pathname === window.location.pathname,
});
if (nav.pathname === window.location.pathname) {
nav.closest('li').classList.add('active')
} else {
nav.closest('li').classList.remove('active')
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418854.html
標籤:
上一篇:如何在Python中為外部庫的函式定義創建自定義輸入型別?
下一篇:改進讀取檔案夾中檔案的功能
