码迷,mamicode.com
首页 > 其他好文 > 详细

基本event封装:阻止冒泡、默认事件等

时间:2014-11-25 15:56:46      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   java   on   div   log   cti   

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
</head>             
<body>
  <div id="box">
   <input type="button" value="按钮3" id="btn3">
   <a href="http://www.sogou.com/sie?hdq=AQxRG-7004&query=addEventListener%20of%20undefined&p=99350103&oq=&ri=-2" id="go">跳转</a>
  </div>
   <script type="text/javascript">
   var btn3 = document.getElementById(‘btn3‘);
   var box = document.getElementById(‘box‘);
   var id = document.getElementById(‘id‘);
   function showMes(event) {
      event = event || window.event;  //在IE8之前要用的是window.event;
	  var ele = event.target || event.srcElement; //在IE8之前用的不是target而是srcElement
      alert(ele.nodeName);
	  event.stopPropagation();
   }
      function showM() {
      alert("RGE");
   }
   function stopGo(event) {
     event.stopPropagation();
	 event.preventDefault();
   }
var eventUtil = {
  //给元素添加事件
   addHandler: function(element, type, handler) {
     if(element.addEventListener) {
	    element.addEventListener(type,handler,false);
	 } else if(element.attachEvent) {
	    element.attachEvent(‘on‘+type, handler);
	 } else {
	    element[‘on‘+type] = handler;
	 }
   },
   //给元素删除事件
     removeHandler: function(element, type, handler) {
     if(element.removeEventListener) {
	    element.removeEventListener(type,handler,false);
	 } else if(element.detachEvent) {
	    element.detachEvent(‘on‘+type, handler);
	 } else {
	    element[‘on‘+type] = null;
	 }
   },
   //获得兼容浏览器的事件对象
   getEvent: function(event) {
     return event?event:window.event;
   },
   //获取事件类型
   getType: function(event) {
      return event.type;
   },
   //获取时间来自哪个元素
   getElement: function(event) {
      return event.target || event.srcElement;
   },
   //阻止取消事件的默认行为
   preventDefault:function(event) {
     if(event.preventDefault) {
	    event.preventDefault();
	 } else {
	    event.returnValue = false;
	 }
   },
   //阻止时间冒泡
   stopPropagation: function(event) {
     if(event.stopPropagation) {
	     event.stopPropagation();
	 } else {
	    event.cancelBubble = true;
	 }
   }
}
eventUtil.addHandler(btn3, ‘click‘, showMes);
eventUtil.addHandler(box, ‘click‘, showM);
eventUtil.addHandler(go, ‘click‘, stopGo);
</script>
</body>
</html>

  

基本event封装:阻止冒泡、默认事件等

标签:blog   http   io   ar   java   on   div   log   cti   

原文地址:http://www.cnblogs.com/zlz-ling/p/4121165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!