我想在懸停任何這個 div 時添加一個類,而不是懸停的那個,我的意思是如果我將滑鼠懸停在數字 2 div 上,如果我將滑鼠懸停在數字 1 和數字 3 div 上3號班將被添加到1號和2號,這可能嗎?
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
uj5u.com熱心網友回復:
兩種解決方案:第一種使用 CSS,第二種使用 JS。
從這個相關的答案中可以看出,不需要 JS:
.wrapper:hover div:not(:hover) {
background: red;
}
<div class="wrapper">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
但如果你真的堅持使用 JS:
- 使用mouseenter 和 mouseleave事件
- 使用Element.classList及其各自的方法
const elDivs = document.querySelectorAll(".wrapper div");
const toggleClassDivs = (evt) => {
const isEnter = evt.type === "mouseenter";
elDivs.forEach(el => el.classList[isEnter ? "add" : "remove"]("red"));
evt.currentTarget.classList.remove("red");
};
elDivs.forEach(el => {
el.addEventListener("mouseenter", toggleClassDivs);
el.addEventListener("mouseleave", toggleClassDivs);
});
.red {background: red;}
<div class="wrapper">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
uj5u.com熱心網友回復:
使用事件mouseenter并mouseleave在它們內部使用for來遍歷所有 div 和 when index === i(i = index = index of hovering div) 然后繼續并且不添加類。像那樣。
let divs = document.querySelectorAll("div");
divs.forEach((div, index) => {
div.addEventListener("mouseenter", () => {
toggleClass(divs, index, true)
})
div.addEventListener("mouseleave", () => {
toggleClass(divs, index, false)
})
})
function toggleClass(divs, index, add){
for(let i = 0; i < divs.length; i ){
if(i === index) continue;
add ? divs[i].classList.add("red") : divs[i].classList.remove("red");
}
}
.red {
background-color:red;
}
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
uj5u.com熱心網友回復:
我在下面的代碼中添加了注釋,以幫助您了解正在發生的事情。在我的示例中,我使用來event.target獲取 的父元素及其兄弟 div 元素。然后你撰寫一個條件來檢查是否等于使用其父元素查詢的 div 元素,如果當前通過回圈的迭代不是,我們添加該類以設定其他 div 的樣式,否則我們有=>我們洗掉類。event.targetevent.targetevent.targetevent.target
最后,我們遍歷事件目標型別和 div,添加事件偵聽器和回呼方法。
// query the div nodeList
let divs = document.querySelectorAll("div");
// array for the event types
const events = ["mouseover", "mouseout"];
// method for toggling your classes
function toggleClass(e) {
// get the parentNode of your event.target element and then query the div elements using that parentNode
// also check that the event.target is not one of the div elements => e.target !== el,
// then check the event.type and add/remove class accordingly
e.target.parentNode.querySelectorAll('div').forEach(el => e.target !== el ?
e.type === "mouseover" ? el.classList.add('change-bg') : el.classList.remove('change-bg') : null)
}
// loop over events and div elements and pass your callback method
events.forEach(ev => {
divs.forEach(div => {
div.addEventListener(ev, toggleClass)
})
})
.change-bg {
background-color: green;
transition: all .3s ease-in-out;
color: yellow;
}
div {
margin-top: 5px;
padding: 5px;
border: 1px solid black;
}
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515381.html
