【问题标题】:Why jquery's mouseover() event occurred at inner element?为什么 jquery 的 mouseover() 事件发生在内部元素?
【发布时间】:2015-05-28 11:48:53
【问题描述】:

我有一个关于 jQuery 的 mouseover 和 mouseout 方法的问题。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
#land {
    background: #FFCC33;
    width: 200px;
    height: 200px;
}

#water {
    background: #33CCCC;
    width: 150px;
    height: 150px;
}

#island {
    background: #33FF33;
    width: 100px;
    height: 100px;
}
</style>
</head>
<body>
    <div id="land">
        <div id="water">
            <div id="island"></div>
        </div>
    </div>
</body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
    $(document).ready(function() {
        $("#land").on({
            "mouseover" : function() {
                console.log("land - mouse over");
            },
            "mouseout" : function() {
                console.log("land - mouse out");
            }
        });
    });
</script>
</html>

当鼠标移动“陆地”->“水”时,鼠标悬停事件发生。 当 'water' -> 'island' 鼠标移出并发生鼠标悬停事件时。

为什么会发生鼠标悬停事件???

【问题讨论】:

  • 岛屿元素包含在水元素中,水元素包含在陆地元素中,所以实际上如果你将鼠标悬停在岛屿上,你就是在陆地、水和岛屿上进行鼠标悬停

标签: jquery mouseover


【解决方案1】:

这就是 mouseovermouseout 的定义方式,当您移动到后代时它也会被触发,并且气泡会在后代中发生事件时触发任何附加到父代的处理程序。

鼠标悬停事件在指针设备移动到 将侦听器附加到其子级之一的元素。

如果您不希望这种情况发生,请使用 mouseentermouseleave 事件

当指针设备(通常是鼠标)时触发 mouseenter 事件 移动到附加了侦听器的元素上。
类似于mouseover,不同之处在于它不是bubble,而是它 当指针从其后代之一移动时不发送 物理空间到它自己的物理空间。

所以当 'water' -> 'island' 发生时,mouseout 会被 water 触发,mouseover 会被island 触发,这些事件会使附加到 land 的处理程序冒泡。

$(document).ready(function() {
   $("#land").on('mouseover mouseout mouseenter mouseleave', function(e) {
     console.log(e.type, e.target.id)
   });
 });
#land {
  background: #FFCC33;
  width: 200px;
  height: 200px;
}
#water {
  background: #33CCCC;
  width: 150px;
  height: 150px;
}
#island {
  background: #33FF33;
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="land">
  <div id="water">
    <div id="island"></div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2011-08-26
    相关资源
    最近更新 更多