mouseover,mouseout,mouseenter,mouseleave的區別

來源:互聯網
上載者:User

標籤:class   blog   code   java   http   tar   

相信做前端開發的都聽說過“冒泡型事件”吧,《JavaScript進階程式設計》第九章有詳細的講述,但是,在學習的時候一知半解,也沒詳細去理解,導致最近在工作中碰到了問題:有許多 li 標籤,標籤上有2個按鈕,若且唯若滑鼠移入 li 時才會顯示上面的2個按鈕,如,左邊是預設狀態,右邊是滑鼠移入狀態,開始使用的是 mouseover 和 mouseout ,結果滑鼠移動到按鈕上時,按鈕會出現閃爍的情況。

    

後來對比了mouseover,mouseout,mouseenter,mouseleave的區別發現,mouseover 和 mouseout 在滑鼠移入移出時會觸發其父級元素的 mouseover,mouseout 方法,而 mouseenter,mouseleave 只會觸發當前滑鼠移入和移出元素的方法。換句話說,後兩者是不冒泡的事件,前兩者是會冒泡的事件。

下面是實驗詳細:

<div id="mouseEventTest">    <span id="parent">aaaaaaaaaaaaaaa<span id="child">bbbbbbbbbb</span></span></div>

頁面如下:

簡單的css代碼:

span{    padding: 10px;    width: auto;    line-height: 30px;}

parent 和 child 的 mouseover,mouseout,mouseenter,mouseleave 方法如下:

    function parentMouseOver(e) {        console.log(‘parentMouseOver‘);    }    function parentMouseOut(e) {        console.log(‘parentMouseOut‘);    }    function childMouseOver(e) {        console.log(‘childMouseOver‘);    }    function childMouseOut(e) {        console.log(‘childMouseOut‘);    }    function parentMouseEnter(e) {        console.log(‘parentMouseEnter‘);    }    function parentMouseLeave(e) {        console.log(‘parentMouseLeave‘);    }    function childMouseEnter(e) {        console.log(‘childMouseEnter‘);    }    function childMouseLeave(e) {        console.log(‘childMouseLeave‘);    }

分別設定兩組綁定:

1)mouseover,mouseout

    $("#parent").bind(‘mouseover‘,parentMouseOver);    $("#parent").bind(‘mouseout‘,parentMouseOut);    $("#child").bind(‘mouseover‘,childMouseOver);    $("#child").bind(‘mouseout‘,childMouseOut);

2)mouseenter,mouseleave

    $("#parent").bind(‘mouseenter‘, parentMouseEnter);    $("#parent").bind(‘mouseleave‘, parentMouseLeave);    $("#child").bind(‘mouseenter‘, childMouseEnter);    $("#child").bind(‘mouseleave‘, childMouseLeave);

操作方式是:滑鼠從 parent 左邊移入,然後從右邊移出。

綁定的結果如下:

1)組(四個紅框分別是:進入 parent ,從 parent 到 child ,從 child  到 parent ,移出 parent):

       

2)組:

    

實驗結果可以清晰地看出 mouseover,mouseout,mouseenter,mouseleave 的區別。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.