js事件处理-整理

<!--

作者:gentiana@163.com

时间:2016-3-10

描述:js事件处理

-->

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>js事件处理</title>

</head>

<body>

<form action="http://www.baidu.com" method="post" >

<button id="btn">按钮123</button>

</form>

<script>

 

//添加事件

var addEvent = function( obj, type, fn ) {

if (obj.addEventListener){

obj.addEventListener( type, fn, false );

}else if (obj.attachEvent) {

obj["e"+type+fn] = fn;

obj.attachEvent( "on"+type, function() {

obj["e"+type+fn].call(obj, window.event);

} );

}

};

 

var test = function(e){

alert('Listener');

stopEvent(e);

}

var test2 = function(){

alert('remove');

}

var btn = document.getElementById('btn');

addEvent(btn, 'click', test);

 

 

//移除事件

 

var removeEvent = function( obj, type, fn ) {

if (obj.removeEventListener){

obj.removeEventListener( type, fn, false );

}

 

else if (obj.detachEvent) {

obj.detachEvent( "on" +type, obj["e"+type+fn] );

obj["e"+type+fn] = null;

}

};

 

 

 

 

//阻止事件(包括冒泡和默认行为)

 

var stopEvent = function(e){

e = e || window.event;

if(e.preventDefault) {

e.preventDefault();

e.stopPropagation();

}else{

e.returnValue = false;

e.cancelBubble = true;

}

};

 

//仅阻止事件冒泡

 

var stopPropagation = function(e) {

e = e || window.event;

if (e.preventDefault) {

e.cancelBubble = true;

} else {

e.stopPropagation();

}

};

 

 

//仅阻止浏览器默认行为

 

var preventDefault = function(e) {

e = e || window.event;

if(e.preventDefault) {

e.preventDefault();

}else{

e.returnValue = false;

}

}

 

//取得事件源对象

 

var getEventTarget = function(e){

e = e || window.event;

var target = event.srcElement ? event.srcElement : event.target;

return target;

};

 

 

</script>

</body>

</html>

posted @ 2016-11-24 10:21  _即炤  阅读(190)  评论(0编辑  收藏  举报