我们知道鼠标经过和离开的事件有俩种:
mouseenter与mouseover,那么这里俩个事件有什么区别呢?
mouseenter:给谁注册的事件,就必须经过谁,才能触发该事件
简单来说mouseenter不能冒泡,也就是说经过其子盒子,不会触发它的事件
而mouseover刚好相反,因为mouseover会冒泡。所以当你经过它的子盒子它也会触发相应事件:
<style> *{ margin: 0; padding: 0; } div{ position: relative; margin-top: 50px; margin-left: 50px; width: 300px; height: 300px; background-color: aquamarine; } a{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); display: block; width: 100px; height: 100px; border: 5px solid #000; padding: 5px; background-color: brown; } em{ position: absolute; top: 5000px; } </style> <body> <div><a href="javascript:;">son</a>father</div> </body> <script> const div = document.querySelector('div') const a = document.querySelector('a') div.addEventListener('mouseover',function(){ console.log('触发了div'); this.style.backgroundColor = 'blue' }) </script>
当鼠标经过son时,必然会先经过father,经过father触发了一次,经过son因为冒泡原理又触发了一次father:
如果我们使用mouseenter呢?
const div = document.querySelector('div') const a = document.querySelector('a') div.addEventListener('mouseenter',function(){ console.log('触发了div'); this.style.backgroundColor = 'blue' })
当鼠标经过son时,必然会先经过father,经过father触发了一次,经过son之后,因为mouseenter不能冒泡,所以没有触发father:
我们可以根据实际情况来判断到底使用哪种鼠标经过事件
mouseenter --> 鼠标经过(不冒泡) | mouseleave -->鼠标离开(不冒泡) |
mouseover -->鼠标经过(冒泡) | mouseout -->鼠标离开(冒泡) |