鼠标悬停和鼠标移动多次触发

时间:2017-01-14 00:08:55

标签: javascript jquery

我在JS中有关于mouseover和mouseout事件的这两个事件。它们用于检查我是否正在我的页面上的面板上盘旋。但问题是当我将鼠标悬停在面板上时它会触发(好),但是当我将鼠标悬停在该面板内的另一个元素上时,它会触发鼠标输出事件,然后当我移动到面板内的另一个部分时再次触发鼠标悬停事件。 / p>

我只希望mouseover和mouseout事件触发一次!一旦进入面板另一个离开它。有没有办法将on mouseover调用传播到div.panel中的所有子元素。似乎这会纠正它。

以下是我的活动

 $(document).off("mouseover").on("mouseover", "div.panel", function() {
   var panelSpaceId = $(this).attr("data-spaceId");
   var marker = _.find(scope.markers, function(item) {
     return item.spaceId == panelSpaceId
   })
   google.maps.event.trigger(marker, "mouseover");
   console.log("over" + marker.spaceId);
 });

 $(document).off("mouseout").on("mouseout", "div.panel", function() {
   var panelSpaceId = $(this).attr("data-spaceId");
   var marker = _.find(scope.markers, function(item) {
     return item.spaceId == panelSpaceId
   })
   google.maps.event.trigger(marker, "mouseout");
   console.log("out" + marker.spaceId);
 });

1 个答案:

答案 0 :(得分:10)

您可以使用mouseenter代替mouseovermouseleave代替mouseout来避免此问题。原因很简单:mouseenter仅在光标“输入”包含其子元素的元素时触发 - 因此将鼠标悬停在元素的子元素上不会重新触发mouseenter事件。

此类似逻辑适用于mouseleave vs mouseout。您可以看到@ {gilly3在based on a fiddle中创建的his answersimilar question发生了这种影响。我没有将您的问题标记为重复,因为您的回答主要是排查mouseover/leave个事件,而不是询问mouseover/entermouseout/leave之间的区别。

想象一下是有帮助的:

  • 输入表示光标进入元素的边界。即使您在子节点中,您仍然在界限内,因此它永远不会被触发多次。
  • (h)overing 可视化为在画布上看到您的元素。如果屏幕上显示光标所在的元素,则会触发鼠标悬停事件。当光标移动超过子元素时,光标不再是超过父元素,因此当你来回反复触发事件时。

这是您修改过的代码,我只是用正确的代码替换了有问题的事件:

$(document).off("mouseenter").on("mouseenter", "div.panel", function() {
  var panelSpaceId = $(this).attr("data-spaceId");
  var marker = _.find(scope.markers, function(item) {
    return item.spaceId == panelSpaceId
  })
  google.maps.event.trigger(marker, "mouseenter");
  console.log("over" + marker.spaceId);
});

$(document).off("mouseleave").on("mouseleave", "div.panel", function() {
  var panelSpaceId = $(this).attr("data-spaceId");
  var marker = _.find(scope.markers, function(item) {
    return item.spaceId == panelSpaceId
  })
  google.maps.event.trigger(marker, "mouseleave");
  console.log("out" + marker.spaceId);
});
相关问题