Javascript初级 JavaScript进阶

JavaScript事件兼容



事件兼容


事件绑定:addEventListener与attachEvent

事件移除:removeEventListener与detachEvent

获取事件对象:e.target与 window.event.srcElement

阻止冒泡:e.stopPropagation与window.event.cancelBubble

阻止默认:e.preventDefault与window.event.returnValue

 


案例


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title></title>

<script src="EventUtil.js" type="text/javascript" charset="utf-8"></script>

</head>

<body>

<input type="button" name="btn1" id="btn1" value="test" />

<br />

<a href="http://www.phpfamily.org" id='myBlog'>个人博客</a>

<div id="box1"><input type="button" value="test1" id='btn2' /></div>

<script type="text/javascript">

var btn1=document.getElementById("btn1");

EventUtil.addHandler(btn1,'click',function(event){

event=EventUtil.getEvent(event);

var target=EventUtil.getTarget(event);

alert(target.tagName);

});

var link=document.getElementById("myBlog");

link.onclick=function(event){

event=EventUtil.getEvent(event);

EventUtil.preventDefault(event);

}

var box1=document.getElementById("box1");

var btn2=document.getElementById("btn2");

box1.onclick=function(event){

alert('div clicked');

}

btn2.onclick=function(event){

alert('button clicked');

event=EventUtil.getEvent(event);

EventUtil.stopPropagation(event);

}

document.body.onclick=function(event){

alert('body clicked');

}

</script>

</body>

</html>


运行结果:


javascript1.png 

(点击即可进入个人博客网站)


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title></title>

<script src="EventUtil.js" type="text/javascript" charset="utf-8"></script>

<script>


window.onload=function(){

var test1=document.getElementById("test1");

test1.onclick=function(){

alert('this is a test');

}

};


</script>

</head>

<body>

<input type="button" value="test1" id='test1'  />

<script type="text/javascript">

//   EventUtil.addHandler(window,'load',function(event){

//    alert('this si atest');

//   });

</script>

</body>

</html>


运行结果:


javascript2.png 


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title></title>

<script src="EventUtil.js" type="text/javascript" charset="utf-8"></script>

</head>

<body>

<!--<p><img src="1.gif" alt="" onload='alert("image loaded")' /></p>-->

<p><img src="1.gif" alt="" id='img'/></p>

<script type="text/javascript">

var img=document.getElementById("img");

EventUtil.addHandler(img,'load',function(event){

event=EventUtil.getEvent(event);

alert(EventUtil.getTarget(event).src);

});

</script>

</body>

</html>



【本文由麦子学院独家原创,转载请注明出处并保留原文链接】

logo
© 2012-2016 www.maiziedu.com
蜀ICP备13014270号-4 Version 5.0.0 release20160127

您有一个双11钜惠红包未领取

客服热线 400-862-8862

回到顶部