问题
I would like div a
and div b
to switch places when the mouse is over div b
then switch back when mouse leaves div a
. But its super glitchy and will switch even when mouse hasn't left div a
. How do i get it to not run navMouseOut
when mouse is still in div a
, and why is it doing this. (please test code to see whats wrong)
document.getElementById("b").onmouseover = function() {
navMouseOver()
};
document.getElementById("a").onmouseout = function() {
navMouseOut()
};
function navMouseOver() {
document.getElementById("a").style = ("top: 50%;");
document.getElementById("b").style = ("top: 40%; ");
}
function navMouseOut() {
document.getElementById("a").style = ("top: 40%;");
document.getElementById("b").style = ("top: 50%;");
}
#a {
position: fixed;
top: 40%;
left: 20%;
background-color: red;
}
#b {
position: fixed;
top: 50%;
left: 20%;
background-color: lightblue;
}
<div id="a">
<p>content a</p>
</div>
<div id="b">
<p>content b...</p>
</div>
回答1:
use onmouseenter instead of onmouseover
document.getElementById("b").onmouseenter = function() {
navMouseOver()
};
document.getElementById("a").onmouseout = function() {
navMouseOut()
};
回答2:
i think the problem is on propagation, let see this function onmouseout,even if you leave your mouse out of P element but still in DIV, onmouseout will still execute.
you can write html like this:
<div id="a">
content a
</div>
<div id="b">
content b...
</div>
or use stoppropagation() or cancelBubble()
回答3:
The problem is that when the elements switch position, the mouseover
and mouseenter
events are fired as the element that is newly positioned on the mouse. To prevent this you can use a flag that is toggled true to false that decides whether or not to run the repositioning code.
var target1 = document.getElementById("mouseoverTarget1");
var switching = false;
var inStartingPosition = true;
target1.addEventListener("mouseover", function() {
if (!switching) {
switching = true;
target1.style.top = inStartingPosition ? "50px" : "0px";
target2.style.top = inStartingPosition ? "-50px" : "0px";
inStartingPosition = inStartingPosition ? false : true;
console.log("mouseover target 1");
setTimeout(() => {
switching = false;
}, 100);
}
});
var target2 = document.getElementById("mouseoverTarget2");
target2.addEventListener("mouseover", function() {
if (!switching) {
switching = true;
target1.style.top = inStartingPosition ? "50px" : "0px";
target2.style.top = inStartingPosition ? "-50px" : "0px";
inStartingPosition = inStartingPosition ? false : true;
console.log("mouseover target 2");
setTimeout(() => {
switching = false;
}, 100);
}
});
#mouseoverTarget1, #mouseoverTarget2 {
width: 50px;
height: 50px;
position: relative;
}
#mouseoverTarget1 {
background-color: red;
}
#mouseoverTarget2 {
background-color: blue;
}
<div id="mouseoverTarget1"></div>
<div id="mouseoverTarget2"></div>
来源:https://stackoverflow.com/questions/43773017/onmouseover-with-javascript