มี invisible element (action bar/menu) อยาก show ตอน mouse enter area ใช้ mouseenter event

HTML Markup
<div class="invisible-box">Yay you can see me!</div>
CSS Styling
.invisible-box {
opacity: 0;
transition: all 500ms;
padding: 32px;
margin-top: 32px;
margin-bottom: 32px;
background-color: #cf4b32;
color: #fff;
text-align: center;
}
.opacity-1 { opacity: 1; }
.invisible-box มี opacity: 0 hidden by default .opacity-1 utility class show element ด้วย JS
JavaScript mouseenter event
let invisibleBox = document.querySelector(".invisible-box");
function addFullOpacity() {
invisibleBox.classList.add("opacity-1");
}
invisibleBox.addEventListener("mouseenter", addFullOpacity);
JS ทำงานอย่างไร
querySelector()หา.invisible-box→ variableinvisibleBox- Function declaration
addFullOpacity()body มี statement - Statement attach
classList.add()เพิ่มopacity-1class addEventListener()2 args: listenmouseenter→ calladdFullOpacity()
mouseenter vs mouseover?
- mouseover trigger ทุกครั้ง mouse move over parent หรือ child elements keep triggering ถ้า move back-forth — expensive performance-wise
- mouseenter trigger เฉพาะ ตอน mouse เข้า target parent element — ไม่สน child elements
ใช้ mouseover ถ้า web component มี features หลายอย่างที่ต้องพฤติกรรมต่างกันตอน interact มิฉะนั้นใช้ mouseenter ดีกว่า performance