js中事件冒泡及阻止冒泡的一小段code

來源:互聯網
上載者:User

標籤:javascript   事件   事件冒泡   

在有些情況下, 事件冒泡會給我們的應用程式帶來負面的影響。 比如下面的例子(有些極端):

<html><head><title></title><script>window.onload = function(){var all = document.getElementsByTagName('*');for(var i = 0; i < all.length; i++){console.log('xxx');all[i].onmouseover = function(e){this.style.border = '1px solid red';}all[i].onmouseout = function(e){this.style.border = '0px';}}}</script></head><body><b>This is the test page</b><ul><li>One</li><li>Two</li><li>Three</li><li><a href='#'>Test link</a></li></ul></body></html>

上面的代碼講的是,為滑鼠移至上方的當前元素加上紅色的邊框。 可以通過為每一個DOM元素增加mouseover和mouseout事件來時間。 如果不阻止事件冒泡, 每次把滑鼠移動到一個元素上時, 該元素都會有紅色的邊框。這並不是我們的預期結果。 效果如下:


那如何解決這類問題呢, 。。。 額, 在這種情況下,當然得阻止時間的冒泡。 那如何阻止? 且看下面的code:

function stopBubble(e){if(e && e.stopPropagation){e.stopPropagation()}else{window.event.cancleBubble = true;}}
每次綁定事件調用上面的函數就可以阻止事件冒泡,從而得到預期的效果。 完整code如下:

<html><head><title></title><script>window.onload = function(){var all = document.getElementsByTagName('*');for(var i = 0; i < all.length; i++){console.log('xxx');all[i].onmouseover = function(e){this.style.border = '1px solid red';stopBubble(e);}all[i].onmouseout = function(e){this.style.border = '0px';stopBubble(e);}}}function stopBubble(e){if(e && e.stopPropagation){e.stopPropagation()}else{window.event.cancleBubble = true;}}</script></head><body><b>This is the test page</b><ul><li>One</li><li>Two</li><li>Three</li><li><a href='#'>Test link</a></li></ul></body></html>
如下:


js中事件冒泡及阻止冒泡的一小段code

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.