我正在看MDN documentation,它说:
mouseenter A pointing device is moved onto the element that has the listener attached.
mouseleave A pointing device is moved off the element that has the listener attached.
mouseover A pointing device is moved onto the element that has the listener attached or onto one of its children.
mouseout A pointing device is moved off the element that has the listener attached or off one of its children.
听起来不错,mouseenter / mouseleave仅在其自身元素上触发,而当这些事件发生在孩子身上时,mouseover / mouse也会触发。
我在这里有一个片段,显示了不同的情况:
const body1 = document.getElementById("mouseenter");
const el1 = document.createElement("div");
body1.append(el1);
const el2 = document.createElement("div");
el2.style = "position: relative; top: -60px;";
el1.append(el2);
const el2b = document.createElement("div");
el1.append(el2b);
const el3 = document.createElement("div");
const el4 = document.createElement("div");
el4.style = "position: relative; top: -60px;";
const el4b = document.createElement("div");
const body2 = document.getElementById("mouseover");
body2.append(el3);
el3.append(el4);
el3.append(el4b);
const inHandler = (event) => {
event.target.className = "in";
}
const outHandler = (event) => {
event.target.className = "out";
}
el1.addEventListener("mouseenter", inHandler);
el1.addEventListener("mouseleave", outHandler);
el2.addEventListener("mouseenter", inHandler);
el2.addEventListener("mouseleave", outHandler);
el2b.addEventListener("mouseenter", inHandler);
el2b.addEventListener("mouseleave", outHandler);
el3.addEventListener("mouseover", inHandler);
el3.addEventListener("mouseout", outHandler);
el4.addEventListener("mouseover", inHandler);
el4.addEventListener("mouseout", outHandler);
el4b.addEventListener("mouseover", inHandler);
el4b.addEventListener("mouseout", outHandler);
div {
border: solid 1px black;
margin: 1em;
padding: 1em;
display: inline-block;
min-width: 50px;
min-height: 50px;
background-color: grey;
}
.in {
background-color: green;
}
.out {
background-color: blue;
}
p {
margin-bottom: 2em;
}
<div id = "mouseenter">
<p>mouseenter/mouseleave</p>
</div>
<div id = "mouseover">
<p>mouseover/mouseout</p>
</div>
现在判断此代码的行为-我想知道该文档中是否有错字。
例如:
对于mouseenter / mouseleave,我希望当您将鼠标悬停在伸出的元素上时,只有那个变成绿色-但父级也变成绿色。
对于鼠标悬停/鼠标悬停,我希望当您将鼠标悬停在伸出的元素上时,只有那个变成绿色-但是父级没有变成绿色。
对于mouseover / mouseout,如果将鼠标悬停在内部元素上,然后退出它,它将变为蓝色,但是我希望父级也变为蓝色。 (尽管我接受这可能是一种竞争条件,在这种情况下它会“重新输入”父元素以使其变为绿色。
有人能解释一下我在这里缺少的有关鼠标事件的细微差别吗?
[我认为W3schools的答案(示例)可以最好地说明
https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_mouseenter_mouseover
对于鼠标悬停在带有事件的进入或退出其中的嵌套s时递增,鼠标进入在进入特定的div区域时递增