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

1.target

  通过获取DOM元素

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

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

但是target方法支持ie9以上的浏览器器,Chrome,ff,IE9以下的是不支持的。

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

    }

  //IE8不支持target方法,为此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;

}

 

  

posted @ 2015-12-21 18:35  素雨雫晴  阅读(1059)  评论(0编辑  收藏  举报