當指針設備移動到存在監聽器的元素或其子元素的時候,事件就會觸發區別:
mouseover, mouseout(有冒泡機制)
mouseenter, mouseleave(無冒泡機制)
代碼伺候:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>hello</title> <script src="js/jquery.js"></script> <style type="text/css"> #test{ width: 300px; height: 400px; border: 1px solid; background-color: skyblue; } #inner{ position: absolute; width: 100px; height: 100px; right: 100px; top: 300px; background-color: aqua; } </style> <body> <div id="test" onmouseover="console.log('hello');"> <div id="inner"></div> </div> </body> </html>
鼠標在inner元素上(也就是綁定了onmouseover事件的test元素的子元素)懸停:執行結果如下圖:
如果覺得不好理解:再看一個例子
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>hello</title> <script src="js/jquery.js"></script> <style type="text/css"> #test{ width: 300px; height: 400px; border: 1px solid; background-color: skyblue; } #inner{ width: 100px; height: 100px; background-color: aqua; } </style> <body> <div id="test" onmouseover="console.log('hello');"> <div id="inner"></div> </div> </body> </html>
運行結果:
如果還是理解不了,可參看JS的事件流機制。
JS的事件流的簡要介紹:
在標准的“DOM2級事件”中規定,事件流首先是經過事件捕獲階段,接着是處於目標階段,最后是事件冒泡階段。這里可以畫個圖示意一下:
首先在事件捕獲過程中,document對象首先接收到click事件,然后事件沿着DOM樹依次向下,一直傳播到事件的實際目標。就是id為btn的標簽。
接着在事件冒泡的過程中,時間開始是由具體的元素(a標簽)接收,然后逐級向上傳播到較為不具體的節點。