5 回答

TA貢獻1862條經(jīng)驗 獲得超7個贊
我認為你可以實現(xiàn)這個保存當前項目:
const menulink = document.querySelectorAll('.menu h6');
let current = null;
for(let item of menulink) {
item.onclick = () => {
if (current) current.style.opacity = '0'
current = item.querySelector('hr')
current.style.opacity = '1'
}
}
hr {
opacity: 0;
}
<div class="menu">
<h6>Home<hr/></h6>
<h6>Movies<hr/></h6>
<h6>TV Shows<hr/></h6>
<h6>Documentaries<hr/></h6>
<h6>Favorites<hr/></h6>
<h6>Collection<hr/></h6>
</div>

TA貢獻1772條經(jīng)驗 獲得超6個贊
看哪!
const menulink = document.querySelectorAll('.menu h6')
let activeHr;
for(let item of menulink) {
item.onclick = (event) => {
if (activeHr) {
activeHr.style.opacity = '0';
}
activeHr = event.currentTarget.querySelector('hr');
activeHr.style.opacity = '1';
}
}
hr {
opacity: 0;
}
<div class="menu">
<h6>Home<hr/></h6>
<h6>Movies<hr/></h6>
<h6>TV Shows<hr/></h6>
<h6>Documentaries<hr/></h6>
<h6>Favorites<hr/></h6>
<h6>Collection<hr/></h6>
</div>

TA貢獻1775條經(jīng)驗 獲得超8個贊
以上所有答案都試圖使您的代碼正常工作-而不是考慮最好的 html 和 CSS-不需要使用 hr-您只需要在元素上設置活動類并讓 CSS 應用邊框底部給它。
這樣標題就不會在點擊時跳轉——我在每個 h6 下添加了一個透明邊框,然后當你點擊它時應用活動類,樣式只是為底部邊框著色。
您不應出于樣式目的使用 html 元素 (hr/) - IMO。
我也不同意在這里使用 h6——這些 o 似乎不是標題……但我把它留了下來,以防代碼比你顯示的更多——例如,如果它們是頁面下方的標題——但是常規(guī)導航列表在這里似乎更合適。
感謝@Barmar 提供了我使用的代碼框架,我同意他使用活動類的方法。請注意,我正在使用空檢查來刪除現(xiàn)有的活動類 - 盡管可以通過簡單地將第一個標題從一開始就設置為活動來緩解這種情況。
const menuLinks = document.querySelectorAll('.menu h6')
for (let menuLink of menuLinks) {
menuLink.onclick = () => {
document.querySelector('.menu h6.active')?.classList.remove('active');
menuLink.classList.add('active');
}
}
.menu h6 {
padding-bottom: 2px;
border-bottom: solid 1px transparent;
transition: all 0.2s ease-in-out
}
.menu h6.active {
border-bottom-color: #000
}
.menu h6:hover {
border-bottom-color: #000;
transition: all 0.25s ease-in-out
}
<div class="menu">
<h6>Home</h6>
<h6>Movies</h6>
<h6>TV Shows</h6>
<h6>Documentaries</h6>
<h6>Favorites</h6>
<h6>Collection</h6>
</div>

TA貢獻1785條經(jīng)驗 獲得超4個贊
不要直接設置樣式,通過 CSS 類的樣式來設置。然后你可以找到當前有類的元素并刪除它,同時將類添加到新選擇的元素。
const menulink = document.querySelectorAll('.menu h6')
for (let item of menulink) {
item.onclick = () => {
let old = document.querySelector('.menu h6 hr.active');
if (old) {
old.classList.remove("active");
}
item.querySelector('hr').classList.add("active");
}
}
.menu h6 hr.active {
opacity: 1;
}
.menu h6 hr {
opacity: 0;
}
<div class="menu">
<h6>Home
<hr/>
</h6>
<h6>Movies
<hr/>
</h6>
<h6>TV Shows
<hr/>
</h6>
<h6>Documentaries
<hr/>
</h6>
<h6>Favorites
<hr/>
</h6>
<h6>Collection
<hr/>
</h6>
</div>
添加回答
舉報