在一个对象上触发某类事件,这个事件会向这个对象的的父级传播,从里到外,直至它被处理或者到达了对象层次的最顶层,即document对象。这个过程就是JavaScript的事件冒泡。
事件冒泡:
在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序,如果没有定义此事件处理程序或事件返回true,那么这个事件会向这个对象的的父级传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活),或者到达了对象层次的最顶层,即document对象。
事件冒泡示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js事件冒泡</title> </head> <style> .outSide{ width:100px; height:100px; background:#000; padding:50px; } .inSide{ width:100px; height:100px; background:#CCC } </style> <body> <div onclick="outSideWork()" id="outSide"> <div onclick="inSideWork()" id="inSide"> </div> </div> </body> <script type="text/JavaScript"> function outSideWork() { alert('My name is outSide,I was working...'); } function inSideWork() { alert('My name is inSide,I was working...'); } </script> </html>
资源搜索网站大全 https://www.renrenfan.com.cn 广州VI设计公司https://www.houdianzi.com
事件冒泡的作用:
(1)事件冒泡允许多个操作被集中处理,(把事件处理器添加到一个父级元素上,避免把事件处理器添加到多个子元素上),它还可以让你在对象层的不同级别捕获事件。
//本例子只在外面盒子定义了处理方法,而这个方法一样可以捕获到子元素点击行为并处理它。假设有成千上万子元素要处理,难道我们要为每个元素加“onclick="eventHandle(event)"”?显然没有这种集中处理的方法来的简单,同时它的性能也是更高的。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js事件冒泡</title> </head> <style> .outSide{ width:100px; height:100px; background:#000; padding:50px; } .inSide{ width:100px; height:100px; background:#CCC } </style> <body> <div onclick="eventHandle(event)" id="outSide"> <div id="inSide"></div> </div> </body> <script> function eventHandle(e){ var e = e||window.event; var obj = e.target || e.srcElement; alert(obj.id +'was click!') } </script> </html>