欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS冒泡事件的快速解決方法

 更新時(shí)間:2013年12月16日 08:47:44   作者:  
這篇文章主要是對(duì)JS冒泡事件的快速解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助

何為冒泡事件
就是當(dāng)設(shè)定了多個(gè)div的嵌套時(shí);即建立了父子關(guān)系,當(dāng)父div與子div共同加入了onclick事件時(shí),當(dāng)觸發(fā)了子div的onclick事件后,子div進(jìn)行相應(yīng)的js操作。但是父div的onclick事件同樣會(huì)被觸發(fā)。這就造成了事件的多層并發(fā),導(dǎo)致了頁(yè)面混亂。這就是冒泡事件。

消除冒泡事件的方法
阻止JavaScript事件冒泡傳遞(cancelBubble 、stopPropagation)

下面的一段代碼即可以很好的解釋是么是冒泡效果,什么叫消除冒泡效果

復(fù)制代碼 代碼如下:

<html>
<head>
<title> 阻止JavaScript事件冒泡傳遞(cancelBubble 、stopPropagation)</title>
<meta name="keywords" content="JavaScript,事件冒泡,cancelBubble,stopPropagation" />
<script type="text/javascript">
function doSomething (obj,evt) {
alert(obj.id);
var e=(evt)?evt:window.event; //判斷瀏覽器的類(lèi)型,在基于ie內(nèi)核的瀏覽器中的使用cancelBubble
if (window.event) {
e.cancelBubble=true;
} else {
//e.preventDefault(); //在基于firefox內(nèi)核的瀏覽器中支持做法stopPropagation
e.stopPropagation();
}
}
</script>
</head>
<body>
<div id="parent1" onclick="alert(this.id)" style="width:250px;background-color:yellow">
<p>This is parent1 div.</p>
<div id="child1" onclick="alert(this.id)" style="width:200px;background-color:orange">
<p>This is child1.</p>
</div>
<p>This is parent1 div.</p>
</div>
<br />
<div id="parent2" onclick="alert(this.id)" style="width:250px;background-color:cyan;">
<p>This is parent2 div.</p>
<div id="child2" onclick="doSomething(this,event);" style="width:200px;background-color:lightblue;">
<p>This is child2. Will bubble.</p>
</div>
<p>This is parent2 div.</p>
</div>
</body>
</html>

把代碼直接復(fù)制后,打開(kāi)當(dāng)點(diǎn)擊child1時(shí)不僅會(huì)彈出 child1 對(duì)話框還會(huì)彈出 parent1

這就是冒泡事件

但是單擊chile2只會(huì)彈出child2卻不會(huì)彈出 parent2,這便是應(yīng)用了阻止冒泡事件的特效的效果.

相關(guān)文章

最新評(píng)論