标签:type round ack ons client alert absolute menu 三层
1. 什么是事件冒泡
在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序;如果没有定义此事件处理程序或者事件返回true,那么这个事件会向这个对象的父级对象传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活),或者它到达了对象层次的最顶层,即document对象(有些浏览器是window)。
2. 事件冒泡的作用
事件冒泡允许多个操作被集中处理(把事件处理器添加到一个父级元素上,避免把事件处理器添加到多个子级元素上),它还可以让你在对象层的不同级别捕获事件。
3. 阻止事件冒泡
事件冒泡机制有时候是不需要的,需要阻止掉,通过 event.stopPropagation() 来阻止
4. 阻止右键菜单
可以在网页上阻止按鼠标右键弹出的默认菜单,然后可以自定义菜单
$(document).contextmenu(function(event) {
event.preventDefault();
});
5. 合并阻止事件冒泡和右键菜单
实际开发中,一般把阻止冒泡和阻止默认行为合并起来写,如下
// event.stopPropagation();
// event.preventDefault();
// 合并写法:
return false;
例子1,验证事件冒泡,搞个三层结构div,并分别定义样式,效果图如下
冒泡的实际效果是:点击红色的子div后,会相继弹出后续的所有click事件。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> .grandfather{ width:300px; height:300px; background-color:green; position:relative; } .father{ width:200px; height:200px; background-color:gold; } .son{ width:100px; height:100px; background-color:red; position:absolute; left:0; top:400px; } </style> <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function(){ $(‘body‘).click(function() { alert(4); }); $(‘.grandfather‘).click(function() { alert(3); }); $(‘.father‘).click(function() { alert(2); }); $(‘.son‘).click(function(ev) { //function中ev的解释:发生click动作时,系统会自动产生一个event对象,这个event可随意写,这里写成了ev alert(1); //ev.stopPropagation(); 加上stopPropagation()后,只会弹出1的框,后续的不会弹出,也就是阻止了事件冒泡 //console.log(ev); 用这个可以看到event对象的所有属性 //alert(ev.clientX); 比如弹出其中的一个event属性:clientX,鼠标点击的X坐标 return false; }); $(document).contextmenu(function(event) { //event.preventDefault(); 阻止网页默认右键菜单 return false; }); }); </script> </head> <body> <div class="grandfather"> <div class="father"> <div class="son"></div> </div> </div> </body> </html>
标签:type round ack ons client alert absolute menu 三层
原文地址:https://www.cnblogs.com/regit/p/9006836.html