jQuery事件冒泡代码实例
分类:实例代码
分享一段代码实例,它演示了事件冒泡的相关特性。
代码实例如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <style> body { padding: 0; margin: 0; width: 1024px; height: 768px; background-color: #c3c3c3; overflow: hidden; position: relative; } .button { width: 50px; height: 50px; top: 200px; left: 200px; position: absolute; background-color: aquamarine; } .refcontent { width: 100px; height: 100px; top: 300px; left: 300px; position: absolute; background-color: red; display: none; } </style> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script> $(document).ready(function(){ $('.button').on('click',function(e){ $('.refcontent').toggle(); e.stopPropagation(); }); $('body').click(function(){ $('.refcontent').hide(); }); $('.refcontent').on('click',function(e){ e.stopPropagation(); }); }); </script> </head> <body> <div class="button"></div> <div class="refcontent"></div> </body> </html>
上面的代码实现了简单的演示,下面简单做一下介绍。
$('.button').on('click',function(e){ $('.refcontent').toggle(); e.stopPropagation(); })
点击此div可以实现refcontent的显示和隐藏的切换,如果没有e.stopPropagation()这段代码,那么refcontent永远都不会弹出来,因为click事件会冒泡到body,于是注册在body的click事件处理函数就会执行,就会将refcontent隐藏。
相关阅读:
(1).事件冒泡可以参阅什么是jquery事件冒泡一章节。
(2).stopPropagation()可以参阅jQuery event.stopPropagation()一章节。
jQuery事件冒泡代码实例,这样的场景在实际项目中还是用的比较多的,关于jQuery事件冒泡代码实例就介绍到这了。
jQuery事件冒泡代码实例属于前端实例代码,有关更多实例代码大家可以查看。