日期:2014-05-16 浏览次数:20358 次
<title>event</title>
<script type="text/javascript" src="tool.js"></script>
<script type="text/javascript" src="demo.js"></script>
</head>
<body>
<input type="button" value="按钮" id="button" />
<a href="http://www.baidu.com" id="a">test</a>
</body>
//跨浏览器添加事件绑定
function addEvent(obj, type, fn) {
if (typeof obj.addEventListener != 'undefined') {
obj.addEventListener(type, fn, false);
} else {
if (!obj.events) obj.events = {};
if (!obj.events[type]) {
obj.events[type] = [];
//把第一次的事件处理函数先储存到第一个位置上
if (obj['on' + type]) obj.events[type][0] = fn;
} else {
//同一个注册函数进行屏蔽,不添加到计数器中
if (addEvent.equal(obj.events[type], fn)) return false;
}
//从第二次开始我们用事件计数器来存储
obj.events[type][addEvent.ID++] = fn;
//执行事件处理函数
obj['on' + type] = addEvent.exec;
}
}
//为每个事件分配一个计数器
addEvent.ID = 1;
//执行事件处理函数
addEvent.exec = function (event) {
var e = event || addEvent.fixEvent(window.event);
var es = this.events[e.type];
for (var i in es) {
es[i].call(this, e);
}
};
//同一个注册函数进行屏蔽
addEvent.equal = function (es, fn) {
for (var i in es) {
if (es[i] == fn) return true;
}
return false;
}
//把IE常用的Event对象配对到W3C中去
addEvent.fixEvent = function (event) {
alert(this+'|');
event.preventDefault = addEvent.fixEvent.preventDefault;
event.stopPropagation = addEvent.fixEvent.stopPropagation;
return event;
};
//IE阻止默认行为
addEvent.fixEvent.preventDefault = function () {
this.returnValue = false;
};
//IE取消冒泡
addEvent.fixEvent.stopPropagation = function () {
this.cancelBubble = true;
};
window.onload = function () {
var oButton = document.getElementById('button');
var a = document.getElementById('a');
addEvent(a, 'click', function (e) {
e.preventDefault();
});
addEvent(oButton, 'click', function (e) {
e.stopPropagation();
alert('button');
});
addEvent(document, 'click', function () {
alert('document');
});
};