javascript-阻止事件冒泡和事件默认行为
1.事件冒泡
(1-1)冒泡是什么?
事件冒泡就像热水沸腾时产生汽泡往上升的情形一样(往上传递的过程),事件冒泡出现的情况:假设一个html结构中两个标签存在父子层级关系,父盒子和子盒子都绑定一个相同的方法时,当点击子盒子时将会触发执行两次方法但实际期待:点击子盒子就单独触发子盒子的事件而不涉及父盒子的方法,解决办法:阻止冒泡.
(1-2)阻止冒泡代码
不同浏览器对阻止冒泡的写法存在兼容问题,在ie浏览器中阻止冒泡的方法是window.event.cancelBubble=true而在谷歌,火狐等浏览器的方法则是e.stopPropagation()
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>javascript阻止冒泡和阻止浏览器默认行为</title>
</head>
<body>
<!--阻止冒泡-->
<div onclick='proPagation(event)'>
<button onclick='proPagation(event)'>按钮</button>
</div>
</body>
<script type='text/javascript'> //预想结果当点击div区域就只弹出一次获取div的元素,当点击button就获取button的元素 //解决方法阻止冒泡 function proPagation(e){ window.event?alert('方法被执行'+(window.event.srcElement)):alert('方法被执行'+e.target)//检测用户点击后触发了什么元素 stopproPagation(e); } //阻止冒泡 function stopproPagation(e){ //为什么用三元表达呢!因为考虑到兼容ie浏览器 window.event?window.event.cancelBubble=true:e.stopPropagation(); } </script>
</html>
2.阻止默认行为
(2-1)默认行为是什么?
浏览器存在自己的默认行为,默认行为是浏览器的默认初始值!有一些浏览器行为是在事件处理程序执行前发生的,也就是说这些默认行为是无法取消的,需要人为去屏蔽浏览器的默认行为.举个常见例子全选页面内容,浏览器跳转到另外一个页面等都属于浏览器的默认行为.
(2-2)阻止默认行为代码?
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>javascript停止冒泡和阻止浏览器默认行为</title>
</head>
<body>
<!--阻止默认行为-->
<a href='http://www.taobao.com' onclick='stoppreevntDefault(event)'>我要跳转到淘宝页面</a>
</body>
<script type='text/javascript'> //阻止默认行为 function stoppreevntDefault(e){ //考虑要兼容ie浏览器 e.preventDefault?e.preventDefault():window.event.returnValue=false; } </script>
</html>
3.第二种阻止默认行为的方法但是不阻止冒泡事件
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>javascript停止冒泡和阻止浏览器默认行为</title>
</head>
<body>
<!--阻止默认行为方法2-->
<div id='div' onclick='alert('div');'>
<ul onclick='alert('ul');'>
<li id='ul-a' onclick='alert('li');'><a href='www.taobao.com'id='testB' );'>superman</a></li>
</ul>
</div>
</body>
<script type='text/javascript'> //阻止默认行为第二种方法 var a = document.getElementById('testB'); a.onclick = function(){ return false; }; </script>
</html>
4.做个假设能不能又阻止默认行为又阻止冒泡呢?
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>javascript停止冒泡和阻止浏览器默认行为</title>
</head>
<body>
<!--判断能不能既阻止默认行为也阻止冒泡事件-->
<div onclick='stopproPagations(event)'>
<a href='http://www.taobao.com' onclick='stopproPagations(event)'>我要跳转到淘宝页面</a>
</div>
</body>
<script type='text/javascript'> function proPagation(e){ window.event?alert('方法被执行'+(window.event.srcElement)):alert('方法被执行'+e.target) stopproPagations(e); } //阻止冒泡和默认行为的方法! function stopproPagations(e){ window.event?window.event.cancelBubble=true:e.stopPropagation(); e.preventDefault?e.preventDefault():window.event.returnValue=false; } </script>
</html>
还没有评论,来说两句吧...