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

来源:互联网 发布:ebpocket 知乎 编辑:程序博客网 时间:2024/06/04 01:11

在有些情况下, 事件冒泡会给我们的应用程序带来负面的影响。 比如下面的例子(有些极端):

<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>
效果图如下:


0 0
原创粉丝点击