javascript阻止事件冒泡和浏览器的默认行为
1.阻止事件冒泡,使成为捕获型事件触发机制.
functionstopBubble(e){
//如果提供了事件对象,则这是一个非IE浏览器
if(e&&e.stopPropagation)
//因此它支持W3C的stopPropagation()方法
e.stopPropagation();
else
//否则,我们需要使用IE的方式来取消事件冒泡
window.event.cancelBubble=true;
}
2.当按键后,不希望按键继续传递给如HTML文本框对象时,可以取消返回值.即停止默认事件默认行为.
//阻止浏览器的默认行为
functionstopDefault(e){
//阻止默认浏览器动作(W3C)
if(e&&e.preventDefault)
e.preventDefault();
//IE中阻止函数器默认动作的方式
else
window.event.returnValue=false;
returnfalse;
}
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metacontent="text/html;charset=utf-8"http-equiv="Content-Type"/>
<title>效果测试</title>
<scriptlanguage="javascript"type="text/javascript"src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>
<scriptlanguage="javascript"type="text/javascript">
$(document).ready(function()
{
$('div.c1').click(function(e){alert('单击了div');});
$('div.c2').click(function(e){alert('单击了div');stopBubble(e);});
$(document).click(function(e){alert('单击了document');});
$('#txt1').val('123');
$('#txt1').click(function(e){stopBubble(e);});
$('#txt1').keydown(function(e){stopDefault(e);alert('你按下了键值'+e.keyCode);});
})
functionstopBubble(e){
//如果提供了事件对象,则这是一个非IE浏览器
if(e&&e.stopPropagation)
//因此它支持W3C的stopPropagation()方法
e.stopPropagation();
else
//否则,我们需要使用IE的方式来取消事件冒泡
window.event.cancelBubble=true;
}
//阻止浏览器的默认行为
functionstopDefault(e){
//阻止默认浏览器动作(W3C)
if(e&&e.preventDefault)
e.preventDefault();
//IE中阻止函数器默认动作的方式
else
window.event.returnValue=false;
returnfalse;
}
</script>
<styletype="text/css">
body{
font-size:14px;
}
}
.c1{
font-family:"ArialUnicodeMS"
}
.c2{
font-family:helvetica,simsun,arial,clean
}
</style>
</head>
<body>
<divclass="c1">测试的文字,这里是样式C1,单击以冒泡的形式触发事件.</div><hr/>
<divclass="c2">测试的文字,这里是样式C2,单击以捕获的形式触发事件.</div><hr/>
<div><inputid="txt1"name="Text1"type="text"/></div><hr/>
</body>
</html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!