1、onmouseover闯团、onmouseout:鼠標(biāo)經(jīng)過(guò)時(shí)自身觸發(fā)事件辛臊,經(jīng)過(guò)其子元素時(shí)也觸發(fā)該事件;(父親有的東西房交,兒子也有)
2彻舰、onmouseenter、onmouseleave:鼠標(biāo)經(jīng)過(guò)時(shí)自身觸發(fā)事件候味,經(jīng)過(guò)其子元素時(shí)不觸發(fā)該事件刃唤。(父親的東西就是父親的,不歸兒子所有)
這四個(gè)事件兩兩配對(duì)使用白群,onmouseover尚胞、onmouseout一對(duì),onmouseenter帜慢、onmouseleave一對(duì)辐真,不能混合使用。
下面來(lái)看例子:
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><style>*{? ? ? ? ? ? margin: 0;? ? ? ? ? ? padding: 0;? ? ? ? }? ? ? ? .f{? ? ? ? ? ? position: relative;? ? ? ? ? ? width: 200px;? ? ? ? ? ? height: 200px;? ? ? ? ? ? background-color: #56b829;? ? ? ? }? ? ? ? .son{? ? ? ? ? ? width: 100px;? ? ? ? ? ? height: 100px;? ? ? ? ? ? position: absolute;? ? ? ? ? ? left: 50%;? ? ? ? ? ? top: 50%;? ? ? ? ? ? margin-left: -50px;? ? ? ? ? ? margin-top: -50px;? ? ? ? ? ? background-color: red;? ? ? ? }</style></head><body><divclass="f"><divclass="son"></div></div><script>let f=document.getElementsByClassName('f')[0];? ? f.onmouseover=function (e) {? ? ? ? console.log('in',e.target);? ? }? ? f.onmouseout=function (e) {? ? ? ? console.log('out',e.target);? ? }</script></body></html>
我們先看下圖再分析
1.gif
我們首先進(jìn)入最外面的div崖堤,可以看到是父div觸發(fā)了mouseover事件侍咱,接著進(jìn)入子div,可以看到父div觸發(fā)了mouseout事件密幔,子div接著觸發(fā)mouseover事件楔脯,然后我們從子div里面出來(lái),可以看到子div觸發(fā)了mouseout事件胯甩,父div觸發(fā)了mouseover事件昧廷,接著我們移出鼠標(biāo),父div觸發(fā)mouseout事件.如果不想子div去觸發(fā)事件偎箫,則可以使用onmouseenter木柬、onmouseleave。
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><style>*{? ? ? ? ? ? margin: 0;? ? ? ? ? ? padding: 0;? ? ? ? }? ? ? ? .f{? ? ? ? ? ? position: relative;? ? ? ? ? ? width: 200px;? ? ? ? ? ? height: 200px;? ? ? ? ? ? background-color: #56b829;? ? ? ? }? ? ? ? .son{? ? ? ? ? ? width: 100px;? ? ? ? ? ? height: 100px;? ? ? ? ? ? position: absolute;? ? ? ? ? ? left: 50%;? ? ? ? ? ? top: 50%;? ? ? ? ? ? margin-left: -50px;? ? ? ? ? ? margin-top: -50px;? ? ? ? ? ? background-color: red;? ? ? ? }</style></head><body><divclass="f"><divclass="son"></div></div><script>let f=document.getElementsByClassName('f')[0];? ? f.onmouseenter=function (e) {? ? ? ? console.log('in',e.target);? ? }? ? f.onmouseleave=function (e) {? ? ? ? console.log('out',e.target);? ? }</script></body></html>
效果如下圖
2.gif