码迷,mamicode.com
首页 > Web开发 > 详细

JS:event对象下的target属性和取消冒泡事件

时间:2015-12-21 20:08:46      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

1.target

  通过获取DOM元素

 var box = document.getElementById("box");
 document.box.onclick = function(){
   alert(123);//123
 }

event对象下的target方法 :获取事件的目标,不用document.getElementById("box")即可获取目标;

  //W3C下
    document.onclick = function(evt){
      var e = evt || window.event;
      alert(e.target.tagName); // DIV ie7 下为undefind

    }

  //ie 下的为srcElement

 document.onclick = function(evt){
   var e = evt || window.event;
   alert(typeof e.srcElement); //DIV
 }

  //兼容所有浏览器

 function getTarget(evt){
   var e = evt || window.event;
   return e.target || e.srcElement;
}

 document.onclick = function(evt){
   alert(getTarget(evt));
 }

 

2.冒泡事件

document.onclick = function () {
  alert(‘document‘);
};
document.documentElement.onclick = function () {
  alert(‘html‘);
};
document.body.onclick = function () {
  alert(‘body‘);
};
document.getElementById("box").onclick = function(){
  alert("div");
}
document.getElementsByTagName("input")[0].onclick =function(evt){
  var e = evt || window.event;
  //e.stopPropagation(); //取消冒泡事件(非IE7以下浏览器)

  //e.cancelBubble = true; //IE7以下浏览器
  setStopBubble(evt); //取消冒泡兼容所有   只会弹出 “input”,其他的不在弹出。
  alert("input");
}

    当点击button按钮之后,会依次弹出input> div> body> html> document,这是有冒泡事件造成的。

  //取消冒泡事件 stopPropagation() /cancelBubble

//兼容所有浏览器
function setStopBubble(evt){
  var e = evt || window.event;
  typeof e.stopPropagation == "function" ? e.stopPropagation():e.cancelBubble = true;

}

 

  

JS:event对象下的target属性和取消冒泡事件

标签:

原文地址:http://www.cnblogs.com/wine/p/5064284.html

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