首先我在网上看到不少文章大体上分为两个(不正确)观点:
1. cancelbubble用于ie的阻止冒泡事件,event.stoppropagation()用于firefox和chrome等其他。
先不讲上面是对是错
先看一个例子:(测试环境:chrom5.0.275.7, moz3.6.4, opera10.53, ie6,7,8)
代码如下:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "https://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
<title>无标题页</title>
</head>
<body onclick="alert('body');">
<input id="button1" type="button" value="button" onclick="clickbtn(event)" />
<script language="javascript" type="text/javascript">
function clickbtn(event)
{
event=event?event:window.event;
event.cancelbubble=true;
alert(event.cancelbubble);
}
</script>
</body>
</html>
. 代码如下:
<script language="javascript" type="text/javascript">
function clickbtn(event)
{
event=event?event:window.event;
event.stoppropagation();
alert("123");
}
</script>
. 代码如下:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "https://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
<title>无标题页</title>
</head>
<body onclick="alert('body');">
<p onclick="clickbtn(event)" style="width:100px;height:100px; background:#666;">
<input id="button1" type="button" value="button" onclick="alert('btn');" />
</p>
<script language="javascript" type="text/javascript">
function clickbtn(event)
{
event=event?event:window.event;
event.stoppropagation();
alert("123");
}
</script>
</body>
</html>
. 代码如下:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "https://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
<title>无标题页</title>
</head>
<body>
<ul id='ul'>
<li id='li1'>list item1</li>
<li id='li2'>list item2</li>
</ul>
<script language="javascript" type="text/javascript">
function init(){
if(!!document.all){
document.getelementbyid('li1').attachevent('onclick', function(event){
alert('li1');
})
document.getelementbyid('li2').attachevent('onclick', function(event){
alert('li2');
})
document.getelementbyid('ul').attachevent('onclick', function(event){
alert('ul');
//event.cancelbubble = true;
alert(event.stoppropagation);
});
}else{
document.getelementbyid('li1').addeventlistener('click', function(event){
alert('li1');
}, true)
document.getelementbyid('li2').addeventlistener('click', function(event){
alert('li2');
}, true)
document.getelementbyid('ul').addeventlistener('click', function(event){
event=event?event:window.event;
event.stoppropagation();
alert('ul');
}, true);
}
}
init();
</script>
</body>
</html>
如对本文有疑问, 点击进行留言回复!!
javascript从入门到跑路-----小文的js学习笔记(19)------- js的垃圾回收机制
Agora 开源 | 一个 Demo,帮你快速实现社交直播四大场景
网友评论