JS 不是合适的工具。 CSS 是一种更好的方法,因为它旨在设置 UI 属性,并且也是硬件加速的,因此比 JS 基于事件的模型性能更好。
您可以使用
:hover
伪选择器来实现您的目标:
.note {
width: 200px;
height: 200px;
position: relative;
background-color: #C00;
}
.note:hover .backgr_color {
background-color: #FFF;
}
.note .backgr_color {
width: 20px;
height: 20px;
background-color: #000;
position: absolute;
top: 90px;
left: 90px;
}
<div class="example" id="example1">
<div class="note">
<div class="backgr_color"></div>
<div class="note_text">
<h2>Text</h2>
<h3>Text</h3>
<div class="note_comment">
<p>Text</p>
</div>
<div class="note_bottom">
<p>text</p>
</div>
</div>
</div>
</div>
<div class="example" id="example1">
<div class="note">
<div class="backgr_color"></div>
<div class="note_text">
<h2>Text</h2>
<h3>Text</h3>
<div class="note_comment">
<p>Text</p>
</div>
<div class="note_bottom">
<p>text</p>
</div>
</div>
</div>
</div>
如果您真的想使用JS执行此操作,那么您可以将事件挂接到循环中的所有
.note
元素,然后使用querySelector()
在引发事件的.backgr_color
中查找.note
元素:
const toggleNoteClass = e => e.target.querySelector('.backgr_color').classList.toggle('hover');
document.querySelectorAll('.note').forEach(note => {
note.addEventListener('mouseenter', toggleNoteClass);
note.addEventListener('mouseleave', toggleNoteClass);
});
.note {
width: 200px;
height: 200px;
position: relative;
background-color: #C00;
}
.note .backgr_color {
width: 20px;
height: 20px;
background-color: #000;
position: absolute;
top: 90px;
left: 90px;
}
.note .backgr_color.hover {
background-color: #FFF;
}
<div class="example" id="example1">
<div class="note">
<div class="backgr_color"></div>
<div class="note_text">
<h2>Text</h2>
<h3>Text</h3>
<div class="note_comment">
<p>Text</p>
</div>
<div class="note_bottom">
<p>text</p>
</div>
</div>
</div>
</div>
<div class="example" id="example1">
<div class="note">
<div class="backgr_color"></div>
<div class="note_text">
<h2>Text</h2>
<h3>Text</h3>
<div class="note_comment">
<p>Text</p>
</div>
<div class="note_bottom">
<p>text</p>
</div>
</div>
</div>
</div>
看来你们关系很亲密。我想你会想向涉及的 html 元素之一添加/删除一个类,并通过 css 处理不同的样式。这是我建议的方法。如果您想删除 mouseleave 上的类,则必须添加另一个事件侦听器。
let notes_animation = document.querySelectorAll(".note");
let backgr_color = document.querySelectorAll(".backgr_color");
for (i = 0; i < notes_animation.length; i++) {
notes_animation[i].addEventListener('mouseenter', function (event) {
event.target.querySelector('.backgr_color').classList.add('foo');
});
}
.note {
display: flex;
}
.backgr_color {
background-color: tomato;
height: 10px;
width: 10px;
}
.backgr_color.foo {
background-color: yellow;
}
<div class="example" id="example1">
<div class="note">
<div class="backgr_color"></div>
<div class="note_text">
<h2>Text</h2>
<h3>Text</h3>
<div class="note_comment">
<p>Text</p>
</div>
<div class="note_bottom">
<p>text</p>
</div>
</div>
</div>
</div>