一、js阻止冒泡 [javascript] view plain copy w3c的方法是e.stopPropagation(),IE则是使用e.cancelBubble = true function myfn(e){ window.event ? window.event.cancelBubble = true : e.stopPropagation(); } 二、js阻止默认行为 [javascript] view plain copy 1、w3c的方法是e.preventDefault(),IE则是使用e.returnValue = false; function myfn(e){ window.event ? window.event.returnValue = false : e.preventDefault(); } 2、普通写法 reutrn false; //在火狐浏览器上是事件绑定该写法不生效 火狐上是事件绑定阻止默认事件要用 e.preventDefault(); 三、总结使用方法 [javascript] view plain copy 1、当需要停止冒泡行为时,可以使用 function stopBubble(e) { //如果提供了事件对象,则这是一个非IE浏览器 if ( e && e.stopPropagation ){ //因此它支持W3C的stopPropagation()方法 e.stopPropagation(); }else{ //否则,我们需要使用IE的方式来取消事件冒泡 window.event.cancelBubble = true; } } 2、当需要阻止默认行为时,可以使用 //阻止浏览器的默认行为 function stopDefault( e ) { //阻止默认浏览器动作(W3C) if ( e && e.preventDefault ){ e.preventDefault(); //IE中阻止函数器默认动作的方式 }else{ window.event.returnValue = false; } } 四、自定义右键菜单 [html] view plain copy <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> * {margin:0; padding:0;} #ul1 {width:100px; background:#CCC; border:1px solid black; position:absolute; display:none;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> document.oncontextmenu=function (ev) { var oEvent=ev||event; var oUl=document.getElementById('ul1'); oUl.style.display='block'; oUl.style.left=oEvent.clientX+'px'; oUl.style.top=oEvent.clientY+'px'; return false; }; document.onclick=function () { var oUl=document.getElementById('ul1'); oUl.style.display='none'; }; </script> </head> <body> <ul id="ul1"> <li>登陆</li> <li>回到首页</li> <li>注销</li> <li>加入VIP</li> </ul> </body> </html> 【事件注意点】 event代表事件的状态,例如触发event对象的元素、鼠标的位置及状态、按下的键等等; event对象只在事件发生的过程中才有效。 firefox里的event跟IE里的不同,IE里的是全局变量,随时可用;firefox里的要用参数引导才能用,是运行时的临时变量。 在IE/Opera中是window.event,在Firefox中是event; 而事件的对象,在IE中是window.event.srcElement,在Firefox中是event.target,Opera中两者都可用。 下面两句效果相同: [javascript] view plain copy function a(e){ var e = (e) ? e : ((window.event) ? window.event : null); var e = e || window.event; // firefox下window.event为null, IE下event为null }