我想要一些東西,當我有一個 addEventListener('mouseover') 時,它會影響他旁邊的兩個元素。
像這樣:
let three = document.getElementById('three');
let six = document.getElementById('six');
intersection3_6.addEventListener("mouseover", function () {
three.classList.add("hover");
six.classList.add("hover");
});
intersection3_6.addEventListener("mouseout", function () {
three.classList.remove("hover");
six.classList.remove("hover");
});
#table {
display: grid;
grid-template-columns: 50px 50px;
grid-template-rows: 50px 50px;
}
#controls {
position: absolute;
height: 100%;
width: 100%;
display: grid;
grid-template-columns: 44px 12px 44px;
grid-template-rows: 50px;
pointer-events: none;
}
#intersection3_6 {
pointer-events: all;
background-color: red;
grid-column-start: 2;
}
.hover {
background-color: aqua;
}
<div id="table">
<button id="three"><span>3</span></button>
<button id="six"><span>6</span></button>
<div id='controls'>
<div class='vertical' id='intersection3_6'></div>
</div>
</div>
它可以作業,但很明顯,當我有這樣的帶有多個交叉點的東西時,它會變得很無聊并且沒有優化到每次都重復自己(我們可以專注于紫色交叉點所在的第一行)
有沒有辦法說“拿你左邊的那個和你右邊的那個然后做這件事”?
uj5u.com熱心網友回復:
回圈遍歷具有相同類的所有元素,并使用 DOM 導航操作到達事件目標旁邊的元素。
document.querySelectorAll(".vertical").forEach(int => {
int.addEventListener('mouseover', (e) => {
let table = e.target.parentElement.parentElement;
table.childElements[0].classList.add('hover');
table.childElements[1].classList.add('hover');
});
int.addEventListener('mouseout', (e) => {
let table = e.target.parentElement.parentElement;
table.childElements[0].classList.remove('hover');
table.childElements[1].classList.remove('hover');
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478302.html
標籤:javascript html css
