onmouseover with javascript

时间:2017-05-04 02:46:57

标签: javascript onmouseover onmouseout

我希望div adiv 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;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

我认为问题出在传播上,让我们看看这个函数onmouseout,即使你将鼠标从P元素中移出但仍然在DIV中,onmouseout仍会执行。

你可以写这样的HTML:

<div id="a">
  content a
</div>
<div id="b">
  content b...
</div>

或使用stoppropagation()或cancelBubble()

答案 1 :(得分:0)

问题是当元素切换位置时,​​mouseovermouseenter事件将作为新定位在鼠标上的元素触发。为了防止这种情况,您可以使用切换为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()
};