javascript停止冒泡和阻止浏览器默认行为

来源:互联网 发布:网络约车平台哪家好 编辑:程序博客网 时间:2024/06/05 19:10

当需要使用冒泡行为时:

function stopBubble(e) { //如果提供了事件对象,则这是一个非IE浏览器 if ( e && e.stopPropagation )     //因此它支持W3C的stopPropagation()方法     e.stopPropagation(); else     //否则,我们需要使用IE的方式来取消事件冒泡     window.event.cancelBubble = true; }

当需要阻止默认行为时:

//阻止浏览器的默认行为 function stopDefault( e ) {     //阻止默认浏览器动作(W3C)     if ( e && e.preventDefault )         e.preventDefault();     //IE中阻止函数器默认动作的方式     else         window.event.returnValue = false;     return false; }

注意点:

1.event 代表事件的状态,例如出发event对象的元素,鼠标的位置及状态,按下的键等

2.event 对象只在事件发生的过程中才有效

firefox里的event跟IE里的不同,IE里的是全局变量,随时可用;firefox里的要用参数引导才能用,是运行时的临时变量。
在IE/Opera中是window.event,在Firefox中是event;而事件的对象,在IE中是window.event.srcElement,在Firefox中是event.target,Opera中两者都可用


下面两句效果相同

function a(e){var e = (e) ? e : ((window.event) ? window.event : null); var e = e || window.event; // firefox下window.event为null, IE下event为null}


参考文章:http://caibaojian.com/javascript-stoppropagation-preventdefault.html

阅读全文
0 0