事件对象
每个事件处理函数中,都可以有一个形参(IE中这个形参无效),系统会自动传递一个事件对象到函数中,这个对象的每个属性都代表事件被触发时的一些关键性数据
IE浏览器中用window.event
来记录触发事件时的关键数据
所以我们如果希望拿到一个事件触发后的事件对象,需要用一种兼容性的写法
div.onclick = function(e){//形参e就是系统传递的事件对象
var event = e || window.event;
console.log(event);
}
一、取消冒泡
1 .W3C标准 event.stopPropagation();
但不支持IE9以下版本
document.onclick = function(){
console.log('aha');
}
div.onclick = function(e){
console.log('orange');
}
点击方块在触发方块点击事件的同时,事件冒泡到document,触发document点击事件
事件对象上的stopPropagation
方法,可以阻止冒泡事件
document.onclick = function(){
console.log('aha');
}
div.onclick = function(e){
e.stopPropagation();
console.log('orange');
}
document的点击事件未被触发
2 .IE独有 现Chrome已实现 event.cancelBubble = true;
div.onclick = function(e){
e.cancelBubble = true;
console.log('orange');
}
能实现同样取消冒泡的效果
封装取消冒泡的函数 stopBubble(event)
div.onclick = function(e){
stopBubble(e);
console.log('orange');
}
function stopBubble(e){
if(e.stopPropagation){
e.stopPropagation()
}else{
e.cancelBubble = true;
}
}
二、阻止默认事件
默认事件—表单提交,a标签跳转、右键菜单等
a标签跳转伴随着页面的自动刷新,是默认事件,即使href属性未指定跳转地址,也会触发页面的刷新
<a href="http://www.baidu.com">百度</a>
<a href="">ss</a>
点击百度,页面会跳转到百度网址
点击ss,页面不会跳转,但会刷新
右键出菜单是个单独的事件
document.oncontextmenu = function(){
console.log('aha')
}
点击右键 输出’aha’的同时会默认弹出菜单(截不到菜单的屏)
1 .return false;
以对象属性的方式绑定的事件才生效
document.oncontextmenu = function(){
console.log('aha');
return false;
}
点击右键,只输出’aha’,不再弹出菜单
var a = document.getElementsByTagName('a')[0];
a.onclick = function(){
return false;
}
点击a标签,页面不会跳转,也不会自动刷新
2 .event.preventDefault();
W3C标注,IE9以下不兼容
document.oncontextmenu = function(e){
console.log('aha');
e.preventDefault();
}
点击右键,只输出’aha’,不再弹出菜单
a.onclick = function(e){
e.preventDefault();
}
点击a标签,页面不会跳转,也不会自动刷新
3 .event.returnValue = false;
兼容IE
document.oncontextmenu = function(e){
console.log('aha');
e.returnValue = false;
}
点击右键,只输出’aha’,不再弹出菜单
a.onclick = function(e){
e.returnValue = false;
}
点击a标签,页面不会跳转,也不会自动刷新
封装阻止默认事件的函数cancelHandler(event)
document.oncontextmenu = function(e){
cancelHandler(e);
console.log('aha');
}
function cancelHandler(event){
if(event.preventDefault){
event.preventDefault()
}else{
event.returnValue = false;
}
}