js阻止冒泡
在阻止冒泡的過程中,W3C和IE采用的不同的方法,那么我們必須做以下兼容。
function stopPro(evt){
var e = evt || window.event;
//returnValue如果設置了該屬性,它的值比事件句柄的返回值優先級高。把這個屬性設置為 fasle,
//可以取消發生事件的源元素的默認動作。
//window.event?e.returnValue = false:e.preventDefault();
window.event?e.cancelBubble=true:e.stopPropagation();
}
或者:
function cancelBubble(e) {
var evt = e ? e : window.event;
if (evt.stopPropagation) {
//W3C
evt.stopPropagation();
}
else {
//IE
evt.cancelBubble = true;
}
JQuery 提供了兩種方式來阻止事件冒泡。
方式一:event.stopPropagation();
$("#div1").mousedown(function(event){
event.stopPropagation();
});
方式二:return false;
$("#div1").mousedown(function(event){
return false;
});
Jquery阻止默認動作即通知瀏覽器不要執行與事件關聯的默認動作。
例如:
$("a").click(function(event){
event.preventDefault(); //阻止默認動作即該鏈接不會跳轉。
alert(4);//但是這個還會彈出
event.stopPropagation();//阻止冒泡事件,上級的單擊事件不會被調用
return false;//不僅阻止了事件往上冒泡,而且阻止了事件本身
});
但是這兩種方式是有區別的。return false 不僅阻止了事件往上冒泡,而且阻止了事件本身。event.stopPropagation() 則只阻止事件往上冒泡,不阻止事件本身。
場景應用:Google 和 百度的聯想框,當彈出下拉列表,用戶在下拉列表區域按下鼠標時需要讓光標仍然保持在文本輸入框。
Jquery案例:
<script src="js/jquery-1.4.3.js"></script>
<script type="text/javascript">
$(function(){
$("#aa").click(function(event){
alert("aa");
event.preventDefault();
event.stopPropagation();
alert(3);
});
$("#ee").click(function(){
alert("ee");
});
$("a").click(function(event){
event.preventDefault();
alert(4);
event.stopPropagation();
return false;
});
});
</script>
</head>
<body>
<div id="ee">
aaaaaaa
<input id="aa" type="button" value="test" />
<a >baidu.com</a>
</div>
</body>
js案例:
function tt(){
alert("div");
}
function ttt(){
var e = arguments.callee.caller.arguments[0] || window.event;
window.event?e.returnValue = false:e.preventDefault();
alert(3);
window.event?e.cancelBubble:e.stopPropagation();
alert(4);
}
</script>
</head>
<body>
<div onclick = "tt();">
ccccc
<a onclick="ttt();">baidu.com</a>
</div>