JavaScript触发了太多事件?

时间:2020-02-19 02:49:28

标签: javascript

句柄mousemove事件在彼此嵌套的3个<div>中。似乎找不到导致引发过多事件的问题。

(function() { 
  var boxes = [ 
    document.getElementById("box1"),
    document.getElementById("box2"),
    document.getElementById("box3"),
  ]; 

  boxes[0].addEventListener(
    "mousemove", function(event) { console.log("Box 1"); }
  ); 
  boxes[1].addEventListener(
    "mousemove", function(event) { console.log("Box 2"); }
  ); 
  boxes[2].addEventListener(
    "mousemove", function(event) { console.log("Box 3"); }
  );
})(); 

3 个答案:

答案 0 :(得分:1)

如果您只是希望在悬停时触发事件,则该事件称为“鼠标悬停”

boxes[0].addEventListener("mouseover", function(event) {
  console.log("Box 1");
});

答案 1 :(得分:1)

您需要使用event.stopPropagation()函数。就像您说的div是嵌套的一样, 因此,

当元素上发生事件时,它首先在上运行处理程序 它,然后在其父节点上,然后一直到其他祖先,这就是事件冒泡

您可以阅读有关here的信息。

看下面的例子,

let box1 = document.querySelector(".box1");
let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");

box1.addEventListener("click",()=> alert("Box1"));
box2.addEventListener("click",()=> alert("Box2"));
box3.addEventListener("click",()=> alert("Box3"));
.box1,.box2,.box3 {
  border: 1px solid;
  padding: 10px;
}
<div class="box1">
  Box 1
  <div class="box2">
    Box 2
    <div class="box3">Box 3</div>
  </div>
</div>

如果单击Box3,也会显示Box2和Box1警报。 原因是Event Bubbling

您可以使用event.stopPropagation()函数停止它

(function() {
  var boxes = [
    document.getElementById("box1"),
    document.getElementById("box2"),
    document.getElementById("box3"),
  ];

  boxes[0].addEventListener("mouseover",
    function(event) {
      event.stopPropagation();
      console.log("Box 1");
    }
  );
  boxes[1].addEventListener("mouseover",
    function(event) {
      event.stopPropagation();
      console.log("Box 2");
    }
  );
  boxes[2].addEventListener("mouseover",
    function(event) {
      event.stopPropagation();
      console.log("Box 3");
    }
  );
})();
#box1,#box2,#box3 {
  border: 1px solid;
  padding: 10px;
}
<div id="box1">
  Box 1
  <div id="box2">
    Box 2
    <div id="box3">Box 3</div>
  </div>
</div>

您只能将事件添加到父元素一次,就像这样

(function() {
  var parentBox = document.getElementById("box1");

  parentBox.addEventListener("click",
    function(event) {
      let targetDiv = event.target;
      switch(targetDiv.id) {
       case "box1" : console.log("Box 1");break;
       case "box2" : console.log("Box 2");break;
       case "box3" : console.log("Box 3");break;
      }      
    },true);
  
})();
#box1,#box2,#box3 {
  border: 1px solid;
  padding: 10px;
}
<div id="box1">
  Box 1
  <div id="box2">
    Box 2
    <div id="box3">Box 3</div>
  </div>
</div>

答案 2 :(得分:0)

请尝试

boxes[0].addEventListener("mousemove", function(event) {
  event.preventDefault();
  event.stopPropogation();
  
  console.log("Box 1");
});