我正在為一個有四個部分的專案撰寫一個簡單的導航欄,并且我使它具有足夠的互動性,以便在懸停/單擊一個部分時具有特定的顏色,然后在單擊后回傳其原始顏色。但是,如果我希望選定的部分在用戶查看時仍然被著色/突出顯示怎么辦?因此,如果懸停顏色編碼為藍色,我希望導航欄中的部分在用戶選擇它時仍為藍色,然后在用戶選擇另一個部分時更改。到目前為止,這是我的代碼。
// The mouse hover functiona and commands. Here we specificy the color of the buttons/mouse
// when the user clicks on them, there's a color for hovering/clicking
// and a color for leaving the button
function mouseOver () {
let anchor = document.getElementsByTagName('a');
for (i = 0; i < anchor.length; i ) {
anchor[i].addEventListener('mouseover', function handleMouseOver() {
event.target.style.backgroundColor = "#72a6ca";
event.target.style.color = "#fff";
})
//the color returns to its normal state after clicking away
anchor[i].addEventListener('mouseout', function handleMouseOut() {
event.target.style.backgroundColor = "rgb(220, 220, 220)";
event.target.style.color = "black";
})
}
}
這是我的導航欄顯示代碼
function navBarStyle () {
let anchor = document.getElementsByTagName('a');
let styles = `
display: flex;
flex-direction: row;
align-items: stretch;
color: #000;
text-decoration: none;
margin: 0 0.5em 0 0.5em;
padding: 0.5em;
background-color: rgb(220, 220, 220);
font-size: large;
transform:translateX(-0.5em);
`;
for (i = 0; i < anchor.length; i ) {
anchor[i].setAttribute('style', styles);
} }
如果我不夠含糊,我很抱歉,但任何幫助將不勝感激,讓我走上正軌
uj5u.com熱心網友回復:
首先,為您當前的實作做一個說明。它可以作業,而且編碼得很好。但是對于這件事,瀏覽器使用 :hover 選擇器提供本機功能,使用它比重新發明它更好。
我沒有您的 HTMl,但您很可能需要為導航中的每個“a”標簽添加一個類,如下所示:
<nav>
<a href="link1" class="nav-link">Link 1</a>
<a href="link2" class="nav-link">Link 2</a>
</nav>
然后你需要在頭部有一個樣式標簽(或者更好,外部css)
<head>
...
<style>
.nav-link {
background-color: 72a6ca;
color: #fff;
}
.nav-link:hover {
background-color: rgb(220, 220, 220);
color: black;
}
</style>
</head>
至于當前部分,您最好的選擇是使用https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
請參閱此處的示例:Intersection Observer API 滾動感知導航
或者這個codepen:https ://codepen.io/mishunov/pen/opeRdL
使用 IntersectionObserver,您可以檢測用戶何時滾動進/出該部分。然后,您可以打開和關閉相關導航鏈接的另一個類。例如 - 假設您切換 .current 類,您的樣式可能看起來像這樣,將兩種情況(懸停和當前滾動)設定在一個位置:
.nav-link:hover,
.nav-link.current {
background-color: rgb(220, 220, 220);
color: black;
}
uj5u.com熱心網友回復:
您可以像這樣使一個名為 active 的類
.active {
backgroundColor: #72a6ca;
color: #fff;
}
并將其分配給單擊(或懸停)的每個錨點,同時.active從其他錨點中洗掉
let anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
anchor.addEventListener('mouseover', function handleMouseOver() {
const target = event.currentTarget;
if (target.classList.contains('active')) {
target.classList.remove('active')
} else {
[...anchors].forEach((anchor) => anchor.classList.remove('active'))
target.classList.add('active')
}
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493284.html
標籤:javascript
上一篇:從收音機中獲取價值,如何優化它?
