標籤: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