{"action":"created","issue":{"url":"https://api.github.com/repos/qianlongo/zepto-analysis/issues/1","repository_url":"https://api.github.com/repos/qianlongo/zepto-analysis","labels_url":"https://api.github.com/repos/qianlongo/zepto-analysis/issues/1/labels{/name}","comments_url":"https://api.github.com/repos/qianlongo/zepto-analysis/issues/1/comments","events_url":"https://api.github.com/repos/qianlongo/zepto-analysis/issues/1/events","html_url":"https://github.com/qianlongo/zepto-analysis/issues/1","id":233621945,"node_id":"MDU6SXNzdWUyMzM2MjE5NDU=","number":1,"title":"mouseenter与mouseover为何这般纠缠不清？","user":{"login":"qianlongo","id":13052156,"node_id":"MDQ6VXNlcjEzMDUyMTU2","avatar_url":"https://avatars3.githubusercontent.com/u/13052156?v=4","gravatar_id":"","url":"https://api.github.com/users/qianlongo","html_url":"https://github.com/qianlongo","followers_url":"https://api.github.com/users/qianlongo/followers","following_url":"https://api.github.com/users/qianlongo/following{/other_user}","gists_url":"https://api.github.com/users/qianlongo/gists{/gist_id}","starred_url":"https://api.github.com/users/qianlongo/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/qianlongo/subscriptions","organizations_url":"https://api.github.com/users/qianlongo/orgs","repos_url":"https://api.github.com/users/qianlongo/repos","events_url":"https://api.github.com/users/qianlongo/events{/privacy}","received_events_url":"https://api.github.com/users/qianlongo/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":0,"created_at":"2017-06-05T15:18:16Z","updated_at":"2018-09-28T08:57:52Z","closed_at":null,"author_association":"OWNER","body":"\r\n## 前言\r\n\r\n[原文地址](https://github.com/qianlongo/zepto-analysis/issues/1)\r\n\r\n[项目地址](https://github.com/qianlongo/zepto-analysis)\r\n\r\n\r\n> 不知道大家在面试或者工作过程中有没有被`mouseover`和`mouseenter`(对应的是`mouseout`和`mouseleave`)事件所困扰。自己之前在面试的时候就有被问到诸如mouseover和mouseenter事件的异同之类的问题？当时没有答出来，一直也对这两个事件有点模糊不清，趁着最近正在读[zepto源码](https://github.com/qianlongo/zepto-analysis)，准备写一篇这方面的文章，如果有错误，请大家指正。\r\n\r\n![](http://odssgnnpf.bkt.clouddn.com/-98ezXklczmayCw28gIX.png)\r\n\r\n<!--more-->\r\n\r\n## mouseenter与mouseover的异同？\r\n\r\n> 要说清楚mouseenter与mouseover有什么不同，也许可以从两方面去讲。\r\n\r\n1. 是否支持冒泡\r\n2. 事件的触发时机\r\n\r\n先来看一张图,对这两个事件有一个简单直观的感受。\r\n\r\n\r\n![](http://odssgnnpf.bkt.clouddn.com/QQ20170605-204232@2x.png)\r\n\r\n**再看看官网对mouseenter的解释**\r\n\r\n[mouseenter | onmouseenter event](https://msdn.microsoft.com/en-us/library/ms536945(v=vs.85).aspx)\r\n\r\n> The event fires only if the mouse pointer is outside the boundaries of the object and the user moves the mouse pointer inside the boundaries of the object. If the mouse pointer is currently inside the boundaries of the object, for the event to fire, the user must move the mouse pointer outside the boundaries of the object and then back inside the boundaries of the object.\r\n\r\n大概意思是说：当鼠标从元素的边界之外移入元素的边界之内时，事件被触发。而当鼠标本身在元素边界内时，要触发该事件，必须先将鼠标移出元素边界外，再次移入才能触发。(英语比较渣😶，凑合看哈)\r\n\r\n> Unlike the onmouseover event, the onmouseenter event does not bubble. \r\n\r\n大概意思是：和mouseover不同的是，mouseenter不支持事件冒泡 (英语比较渣😶，凑合看哈)\r\n\r\n**由于mouseenter不支持事件冒泡，导致在一个元素的子元素上进入或离开的时候会触发其mouseover和mouseout事件，但是却不会触发mouseenter和mouseleave事件**\r\n\r\n我们用一张动图来看看他们的区别([或者点击该链接体验](https://qianlongo.github.io/zepto-analysis/example/event/mouseEnter-mouseOver.html))。\r\n\r\n![](http://odssgnnpf.bkt.clouddn.com/undefeind.gif)\r\n\r\n我们给左右两边的ul分别添加了`mouseover`和`mouseenter`事件，当鼠标进入左右两边的ul时，`mouseover`和`mouseenter`事件都触发了，但是当移入各自的子元素li的时候，触发了左边ul上的mouseover事件，然而右边ul的mouseenter事件没有被触发。\r\n\r\n造成以上现象本质上是`mouseenter`事件不支持冒泡所致。\r\n\r\n## 如何模拟mouseenter事件。\r\n\r\n> 可见mouseover事件因其具有冒泡的性质，在子元素内移动的时候，频繁被触发，如果我们不希望如此，可以使用mouseenter事件代替之，但是早期只有ie浏览器支持该事件，虽然现在大多数高级浏览器都支持了mouseenter事件，但是难免会有些兼容问题，所以如果可以自己手动模拟，那就太好了。\r\n\r\n\r\n关键因素: **relatedTarget** 要想手动模拟mouseenter事件，需要对mouseover事件触发时的事件对象event属性relatedTarget了解。\r\n\r\n1. relatedTarget事件属性返回与事件的目标节点相关的节点。\r\n2. 对于mouseover事件来说，该属性是鼠标指针移到目标节点上时所离开的那个节点。\r\n3. 对于mouseout事件来说，该属性是离开目标时，鼠标指针进入的节点。\r\n4. 对于其他类型的事件来说，这个属性没有用。\r\n\r\n重新回顾一下文章最初的那张图，根据上面的解释，对于ul上添加的mouseover事件来说，relatedTarget只可能是\r\n\r\n1. ul的父元素wrap(移入ul时,此时也是触发mouseenter事件的时候, **其实不一定，后面会说明**)，\r\n2. 或者ul元素本身(在其子元素上移出时)，\r\n3. 又或者是子元素本身(直接从子元素A移动到子元素B)。\r\n\r\n![relatedTarget](http://odssgnnpf.bkt.clouddn.com/hahha2.png)\r\n\r\n根据上面的描述，我们可以对relatedTarget的值进行判断：如果值不是目标元素，也不是目标元素的子元素，就说明鼠标已移入目标元素而不是在元素内部移动。\r\n\r\n条件1： **不是目标元素**很好判断`e.relatedTarget !== target(目标元素)`\r\n\r\n条件2：不是目标元素的子元素，这个应该怎么判断呢？\r\n\r\n## ele.contains\r\n\r\n>  这里需要介绍一个新的api [node.contains(otherNode) \r\n](https://developer.mozilla.org/zh-CN/docs/Web/API/Node/contains), 表示传入的节点是否为该节点的后代节点, 如果 otherNode 是 node 的后代节点或是 node 节点本身.则返回true , 否则返回 false\r\n\r\n**用法案例**\r\n\r\n``` html\r\n\r\n<ul class=\"list\">\r\n  <li class=\"item\">1</li>\r\n  <li>2</li>\r\n</ul>\r\n<div class=\"test\"></div>\r\n\r\n```\r\n\r\n``` javascript\r\nlet $list = document.querySelector('.list')\r\nlet $item = document.querySelector('.item')\r\nlet $test = document.querySelector('.test')\r\n\r\n$list.contains($item) // true\r\n$list.contains($test) // false\r\n$list.contains($list) // true\r\n\r\n```\r\n\r\n那么利用contains这个api我们便可以很方便的验证条件2，接下来我们封装一个`contains(parent, node)`函数，专门用来判断`node`是不是`parent`的子节点\r\n\r\n``` javascript\r\n\r\nlet contains = function (parent, node) {\r\n  return parent !== node && parent.contains(node)\r\n}\r\n\r\n\r\n```\r\n\r\n用我们封装过后的`contains`函数再去试试上面的例子\r\n\r\n``` javascript\r\ncontains($list, $item) // true\r\ncontains($list, $test) // false\r\ncontains($list, $list) // false (主要区别在这里)\r\n\r\n```\r\n\r\n这个方法很方便地帮助我们解决了模拟mouseenter事件中的条件2，但是悲催的`ode.contains(otherNode)`,具有浏览器兼容性，在一些低级浏览器中是不支持的，为了做到兼容我们再来改写一下contains方法\r\n\r\n``` javascript\r\nlet contains = docEle.contains ? function (parent, node) {\r\n  return parent !== node && parent.contains(node)\r\n} : function (parent, node) {\r\n  let result = parent !== node\r\n\r\n  if (!result) { // 排除parent与node传入相同的节点\r\n    return result\r\n  }\r\n\r\n  if (result) {\r\n    while (node && (node = node.parentNode)) {\r\n      if (parent === node) {\r\n        return true\r\n      }\r\n    }\r\n  }\r\n\r\n  return false\r\n}\r\n\r\n```\r\n\r\n说了这么多，我们来看看用`mouseover`事件模拟`mouseenter`的最终代码\r\n\r\n\r\n``` javascript\r\n\r\n// callback表示如果执行mouseenter事件时传入的回调函数\r\n\r\nlet emulateEnterOrLeave = function (callback) {\r\n  return function (e) {\r\n    let relatedTarget = e.relatedTarget\r\n    if (relatedTarget !== this && !contains(this, relatedTarget)) {\r\n      callback.apply(this, arguments)\r\n    }\r\n  }\r\n}\r\n\r\n```\r\n\r\n**模拟mouseenter与原生mouseenter事件效果对比**\r\n\r\n`html`\r\n\r\n``` html\r\n<div class=\"wrap\">\r\n  wrap, mouseenter\r\n  <ul class=\"mouseenter list\">\r\n    count: <span class=\"count\"></span>\r\n    <li>1</li>\r\n    <li>2</li>\r\n    <li>3</li>\r\n  </ul>\r\n</div>\r\n\r\n<div class=\"wrap\">\r\n  wrap, emulate mouseenter,用mouseover模拟实现mouseenter\r\n  <ul class=\"emulate-mouseenter list\">\r\n    count: <span class=\"count\"></span>\r\n    <li>1</li>\r\n    <li>2</li>\r\n    <li>3</li>\r\n  </ul>\r\n</div>\r\n\r\n```\r\n\r\n`css`\r\n\r\n``` s\r\n.wrap{\r\n  width: 50%;\r\n  box-sizing: border-box;\r\n  float: left;\r\n}\r\n\r\n.wrap, .list{\r\n  border: solid 1px green;\r\n  padding: 30px;\r\n  margin: 30px 0;\r\n}\r\n\r\n.list{\r\n  border: solid 1px red;\r\n}\r\n\r\n.list li{\r\n  border: solid 1px blue;\r\n  padding: 10px;\r\n  margin: 10px;\r\n}\r\n\r\n.count{\r\n  color: red;\r\n}\r\n\r\n```\r\n\r\n`javascript`\r\n\r\n``` javascript\r\nlet $mouseenter = document.querySelector('.mouseenter')\r\nlet $emulateMouseenter = document.querySelector('.emulate-mouseenter')\r\nlet $enterCount = document.querySelector('.mouseenter .count')\r\nlet $emulateMouseenterCounter = document.querySelector('.emulate-mouseenter .count')\r\n\r\nlet addCount = function (ele, start) {\r\n  return function () {\r\n    ele.innerHTML = ++start\r\n  }\r\n}\r\n\r\nlet docEle = document.documentElement\r\n  let contains = docEle.contains ? function (parent, node) {\r\n    return parent !== node && parent.contains(node)\r\n  } : function (parent, node) {\r\n  let result = parent !== node\r\n\r\n  if (!result) {\r\n    return result\r\n  }\r\n\r\n  if (result) {\r\n    while (node && (node = node.parentNode)) {\r\n      if (parent === node) {\r\n        return true\r\n      }\r\n    }\r\n  }\r\n\r\n  return false\r\n}\r\n\r\nlet emulateMouseenterCallback = addCount($emulateMouseenterCounter, 0)\r\n  \r\nlet emulateEnterOrLeave = function (callback) {\r\n  return function (e) {\r\n    let relatedTarget = e.relatedTarget\r\n    if (relatedTarget !== this && !contains(this, relatedTarget)) {\r\n      callback.apply(this, arguments)\r\n    }\r\n  }\r\n}\r\n\r\n$mouseenter.addEventListener('mouseenter', addCount($enterCount, 0), false)\r\n$emulateMouseenter.addEventListener('mouseover', emulateEnterOrLeave(emulateMouseenterCallback), false)  \r\n\r\n```\r\n\r\n**效果预览**\r\n\r\n![](http://odssgnnpf.bkt.clouddn.com/emulateMouseenter2.gif)\r\n\r\n\r\n\r\n[详细代码点击](https://github.com/qianlongo/zepto-analysis/blob/master/example/event/emlateMouseenter.html)\r\n\r\n[代码示例点击](https://qianlongo.github.io/zepto-analysis/example/event/emlateMouseenter.html)\r\n\r\n**好了，我们已经通过mouseove事件完整的模拟了mouseenter事件，但是反过头来看看**\r\n\r\n\r\n对于ul上添加的mouseover事件来说，relatedTarget只可能是\r\n\r\n1. ul的父元素wrap(移入ul时,此时也是触发mouseenter事件的时候, **其实不一定，后面会说明**)，\r\n2. 或者ul元素本身(在其子元素上移出时)，\r\n3. 又或者是子元素本身(直接从子元素A移动到子元素B)。\r\n\r\n我们通过排查2和3，最后只留下1，也就是mouseenter与mouseover事件一起触发的时机。既然这样我们为什么不像这样判断呢？\r\n\r\n``` javascript\r\ntarget.addEventListener('mouseover', function (e) {\r\n  if (e.relatedTarget === this.parentNode) {\r\n    // 执行mouseenter的回调要做的事情  \r\n  }\r\n}, false)\r\n\r\n\r\n```\r\n\r\n这样不是更加简单吗？，何必要折腾通过排查2和3来做？\r\n\r\n原因是，target的父元素有一定的占位空间的时后，我们这样写是没有太大问题的，但是反之，这个时候`e.relatedTarget`就可能是target元素的父元素，又祖先元素中的某一个。我们无法准确判断e.relatedTarget到底是哪个元素。所以通过排除2和3应该是个更好的选择。\r\n\r\n## 用mouseout模拟mouseleave事件\r\n\r\n> 当mouseout被激活时，relatedTarget表示鼠标离开目标元素时，进入了哪个元素，我们同样可以对relatedTarget的值进行判断：如果值不是目标元素，也不是目标元素的子元素，就说明鼠标已移出目标元素\r\n\r\n我们同样可以用上面封装的函数完成\r\n\r\n``` javascript\r\n\r\n// callback表示如果执行mouseenter事件时传入的回调函数\r\n\r\nlet emulateEnterOrLeave = function (callback) {\r\n  return function (e) {\r\n    let relatedTarget = e.relatedTarget\r\n    if (relatedTarget !== this && !contains(this, relatedTarget)) {\r\n      callback.apply(this, arguments)\r\n    }\r\n  }\r\n}\r\n\r\n```\r\n\r\n[详细代码点击](https://github.com/qianlongo/zepto-analysis/blob/master/example/event/mouseEnter-mouseOver.html)\r\n\r\n[代码示例点击](https://qianlongo.github.io/zepto-analysis/example/event/mouseEnter-mouseOver.html)\r\n\r\n## 结尾\r\n\r\n> 文中也许有些观点不够严谨，欢迎大家拍砖。\r\n\r\n\r\n[原文地址](https://github.com/qianlongo/zepto-analysis/issues/1)\r\n\r\n[项目地址](https://github.com/qianlongo/zepto-analysis)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"},"comment":{"url":"https://api.github.com/repos/qianlongo/zepto-analysis/issues/comments/425370274","html_url":"https://github.com/qianlongo/zepto-analysis/issues/1#issuecomment-425370274","issue_url":"https://api.github.com/repos/qianlongo/zepto-analysis/issues/1","id":425370274,"node_id":"MDEyOklzc3VlQ29tbWVudDQyNTM3MDI3NA==","user":{"login":"lazybonee","id":11715201,"node_id":"MDQ6VXNlcjExNzE1MjAx","avatar_url":"https://avatars0.githubusercontent.com/u/11715201?v=4","gravatar_id":"","url":"https://api.github.com/users/lazybonee","html_url":"https://github.com/lazybonee","followers_url":"https://api.github.com/users/lazybonee/followers","following_url":"https://api.github.com/users/lazybonee/following{/other_user}","gists_url":"https://api.github.com/users/lazybonee/gists{/gist_id}","starred_url":"https://api.github.com/users/lazybonee/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/lazybonee/subscriptions","organizations_url":"https://api.github.com/users/lazybonee/orgs","repos_url":"https://api.github.com/users/lazybonee/repos","events_url":"https://api.github.com/users/lazybonee/events{/privacy}","received_events_url":"https://api.github.com/users/lazybonee/received_events","type":"User","site_admin":false},"created_at":"2018-09-28T08:57:52Z","updated_at":"2018-09-28T08:57:52Z","author_association":"NONE","body":"感谢楼主的分享！讲得很详细很全面，但我有一点不明白的是文中说：“ul的父元素wrap(移入ul时,此时也是触发mouseenter事件的时候, 其实不一定，后面会说明)“,但是文中好像没有解释，请问在什么情况下不会触发mouseenter呢"}}
{"actor":{"display_login":"lazybonee"}}