Maison > interface Web > js tutoriel > le corps du texte

阻止事件冒泡

巴扎黑
Libérer: 2016-11-25 13:33:52
original
915 Les gens l'ont consulté

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

事件兼容 

Js代码  

function myfn(e){  

    var evt = e ? e:window.event;  

}  



js停止冒泡 

Js代码  

function myfn(e){  

    window.event? window.event.cancelBubble = true : e.stopPropagation();  

}  



js阻止默认行为 

Js代码  

function myfn(e){  

    window.event? window.event.returnValue = false : e.preventDefault();  

}  



js阻止冒泡: 
w3c的方法是e.stopPropagation(),IE则是使用e.cancelBubble = true。 

stopPropagation也是事件对象(Event)的一个方法,作用是阻止目标元素的冒泡事件,但是会不阻止默认行为。 

js阻止默认行为: 
w3c的方法是e.preventDefault(),IE则是使用e.returnValue = false; 

preventDefault它是事件对象(Event)的一个方法,作用是取消一个目标元素的默认行为。 
既然是说默认行为,当然是元素必须有默认行为才能被取消,如果元素本身就没有默认行为,调用当然就无效了。 

什么元素有默认行为呢?如链接,提交按钮等。 
当Event 对象的 cancelable为false时,表示没有默认行为,这时即使有默认行为,调用preventDefault也是不会起作用的。 

return false: 
javascript的return false只会阻止默认行为,而是用jQuery的话则既阻止默认行为又防止对象冒泡。 

总结使用方法: 
当需要停止冒泡行为时,可以使用 

Js代码  

function stopBubble(e) {   

//如果提供了事件对象,则这是一个非IE浏览器   

if ( e && e.stopPropagation )   

    //因此它支持W3C的stopPropagation()方法   

    e.stopPropagation();   

else   

    //否则,我们需要使用IE的方式来取消事件冒泡   

    window.event.cancelBubble = true;   

}  



当需要阻止默认行为时,可以使用: 

Js代码  

//阻止浏览器的默认行为   

function stopDefault( e ) {   

    //阻止默认浏览器动作(W3C)   

    if ( e && e.preventDefault )   

        e.preventDefault();   

    //IE中阻止函数器默认动作的方式   

    else   

        window.event.returnValue = false;   

    return false;   

}  



事件注意点: 

event代表事件的状态,例如触发event对象的元素、鼠标的位置及状态、按下的键等等; 
event对象只在事件发生的过程中才有效。 

firefox里的event跟IE里的不同,IE里的是全局变量,随时可用; 
firefox里的要用参数引导才能用,是运行时的临时变量。 
在IE/Opera中是window.event,在Firefox中是event; 

而事件的对象,在IE中是window.event.srcElement, 
在Firefox中是event.target,Opera中两者都可用。 

下面两句效果相同: 

Js代码  

//code from http://caibaojian.com/javascript-stoppropagation-preventdefault.html  

function a(e){  

var e = (e) ? e : ((window.event) ? window.event : null);   

var e = e || window.event; // firefox下window.event为null, IE下event为null  

}  


source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!