JavaScript之事件的中断传播与行为阻止
Created at 2016-07-27
Updated at 2017-01-06
Category
Front-End
Tag
JavaScript
- 如何中断事件的传播?
stopPropagation()
w3c
取消冒泡
cancleBubble = true
IE
取消冒泡
取消事件默认效果:
returnValue = false
IE
取消事件效果
defaultPrevent()
w3c
取消事件效果
1 2 3 4 5
| <div id='aa'> <div id='bb'> <div id ='cc'></div> </div> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #aa{ width: 600px; height: 600px; background: gray; } #bb{ width: 400px; height: 400px; background: green; } #cc{ width: 200px; height: 200px; background: red; }
|
1 2 3
| document.getElementById('aa').addEventListener('click',function (ev){alert('aa');ev.stopPropagation();},true); document.getElementById('bb').addEventListener('click',function (){alert('bb')},true); document.getElementById('cc').addEventListener('click',function (){alert('cc')},true);
|
1 2 3 4 5 6 7 8 9
| document.getElementById('aa').addEventListener('click',function (){alert('aa');}); document.getElementById('bb').addEventListener('click',function (){alert('bb')}); document.getElementById('cc').addEventListener('click', function (ev){ alert('cc'); ev.stopPropagation(); }); }
|
取消事件效果
- returnValue = false //IE 取消事件效果
- preventDefault() //w3c取消事件效果
1 2 3 4 5 6 7 8
| document.getElementsByTagName('a')[0].onclick = function (ev){ alert('点击'); ev.preventDefault(); alert('已经拦截'); }
|