`
bazhuang
  • 浏览: 147433 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

屏蔽dom的上级节点的事件

阅读更多
由于网页中的节点会继承上级节点的事件,可有时候这个事件继承并不是我们需要的,所以就需要对它进行屏蔽,一般我们写上event.cancelBubble=true;就可以解决了,但这个并不一定适用于所有事件以及适应大部分浏览器。
下面的这个方法就可以解决这个问题,代码如下:
以下是html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title> new document </title>
 </head>
 <body>
 <div id="parentN" style="height:300px;background-color:#EEEEEE;">
 <button id="bt" style="border:1px solid windowtext;background-color:#C3EFEF;">屏蔽上级dom的click事件</button>
 </div>
 </body>
</html>

以下是js代码:
  <script>

Event = function(e){
	this.et = e;
}

Event.prototype.stopEvent = function(){
	this.stopPropagation();
	this.preventDefault();
}

Event.prototype.stopPropagation = function(){
	var ev = this.et;
    if (ev.stopPropagation) {
        ev.stopPropagation();
    } else {
        ev.cancelBubble = true;
    }
}

Event.prototype.preventDefault = function(){
	var ev = this.et;
    if(ev.preventDefault) {
        ev.preventDefault();
    } else {
        ev.returnValue = false;
    }
}

Event.on = function(dom,eventName,callFunc,scope,config){
	var scope = scope||window;
	var config = config || {};
	var h = function(e){
		var evt = window.event || e;
		callFunc.call(scope,evt,config);
	}
	if(eventName == "mousewheel" && dom.addEventListener){ 
        dom.addEventListener("DOMMouseScroll", h, false);
    }
	else{
		if(window.attachEvent){
			dom.attachEvent("on"+eventName, h);
		}
		else if(window.addEventListener){
			dom.addEventListener(eventName, h,false);
		}
	}
}

function divClick(e){
	alert("您当前点击的是div");
	var ev = new Event(e);
	ev.stopEvent();
}

function buttonClick(e){
	var ev = new Event(e);
	ev.stopEvent();
	alert("您当前点击的是button");
}

function onScroll(e){
	var ev = new Event(e);
	ev.stopEvent();
}

window.onload = function(){
	Event.on(document.getElementById("parentN"),"click",divClick,window);
	Event.on(document.getElementById("parentN"),"contextmenu",divClick,window);
	Event.on(document.getElementById("bt"),"click",buttonClick,window);
	Event.on(document.getElementById("bt"),"contextmenu",function(e){
		var ev = new Event(e);
	ev.stopEvent();
	},window);

}
  </script>


这样就可以保证在div上单击时提示的是“您当前点击的是div”,而在按钮上单击时显示的是“您当前点击的是button”,这句“您当前点击的是div”就不会显示了。
同样在div上点右键也会提示“您当前点击的是div”,而在按钮上右键就不会提示了,
var ev = new Event(e);
ev.stopEvent();

关键就是上面这句代码,这个参数e就是event了。

以上代码在ie以及firefox中测试通过。
0
0
分享到:
评论
1 楼 erfeiqi 2008-02-21  
这个做法不错

相关推荐

Global site tag (gtag.js) - Google Analytics