我希望div a
和div b
在鼠标移过div b
时切换位置,然后在鼠标离开div a
时切换回来。但它的超级小故障,即使鼠标没有离开div a
也会切换。当鼠标仍处于navMouseOut
时,如何将其设置为不运行div a
,为什么会这样做呢? (请测试代码以查看错误)
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>
&#13;
答案 0 :(得分:0)
我认为问题出在传播上,让我们看看这个函数onmouseout,即使你将鼠标从P元素中移出但仍然在DIV中,onmouseout仍会执行。
你可以写这样的HTML:
<div id="a">
content a
</div>
<div id="b">
content b...
</div>
或使用stoppropagation()或cancelBubble()
答案 1 :(得分:0)
问题是当元素切换位置时,mouseover
和mouseenter
事件将作为新定位在鼠标上的元素触发。为了防止这种情况,您可以使用切换为true的标志来决定是否运行重新定位代码。
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>
答案 2 :(得分:-1)
使用onmouseenter而不是onmouseover
document.getElementById("b").onmouseenter = function() {
navMouseOver()
};
document.getElementById("a").onmouseout = function() {
navMouseOut()
};