这取决于你想回多远。在 IE8 上,您可以扩展 Element.prototype 以向所有 HTML 元素添加功能,这至少完成了 90% 的工作。我相当肯定你不能在 IE6 中做到这一点(PrototypeJS 不得不求助于扩展单个 Element 实例),我不记得 IE7。不过,除非您的目标是东亚市场,否则您基本上可以忽略 IE7 及更早版本。
以下是您如何执行此操作的示例:
(function() {
// Functions for IE
function stopPropagation() {
this.cancelBubble = true;
}
function preventDefault() {
this.returnValue = false;
}
function addEventUsingAttach(eventName, handler)
{
this.attachEvent("on" + eventName, function() {
var e = window.event;
e.stopPropagation = stopPropagation;
e.preventDefault = preventDefault;
handler.call(this, e);
});
}
// Function to add `addEvent` to the given target object
function extendIt(target)
{
if (target.addEventListener) {
target.addEvent = Element.prototype.addEventListener;
}
else {
target.addEvent = addEventUsingAttach;
}
}
// Add it to `Element.prototype` if we have it
if (typeof Element !== "undefined" &&
typeof Element.prototype !== "undefined") {
extendIt(Element.prototype);
}
// Add it to `window` and `document` (etc.)
extendIt(window);
extendIt(document);
})();
Live Example | Source
然后您手动扩展其他 EventTargets,例如 window 和 document(参见上面代码清单的末尾)。
原始答案:我最初误解了您的问题是关于添加 addEventListener,特别是在 IE8 上,而实际上您的问题很明显不是关于添加,但添加您自己的addEvent。我将把这个答案留给其他读者:
这取决于你想回多远。在 IE8 上,您可以扩展 Element.prototype 以向其添加 addEventListener,这将被页面上的所有 HTML 元素使用(见下文)。但是,您添加的 shim 不支持捕获阶段,因为 IE 不支持它,直到它们原生支持 addEventListener。我很确定你不能在早期版本(IE7、IE6)上扩展Element.prototype,PrototypeJS 不得不退回到为旧版本的 IE 扩展特定元素。但它适用于 IE8。
扩展了Element.prototype,那么您必须手动扩展您提到的其他事件目标,但扩展Element.prototype 可以完成大部分工作。
但是,如果您这样做并包含第三方脚本,请注意它们可能会假定 addEventListeneer 的正确实现已完成捕获阶段。
这是将addEventListener 添加到 IE8 的基本 shim:
(function() {
function stopPropagation() {
this.cancelBubble = true;
}
function preventDefault() {
this.returnValue = false;
}
if (typeof Element !== "undefined" &&
typeof Element.prototype !== "undefined" &&
!Element.prototype.addEventListener) {
Element.prototype.addEventListener = function(eventName, handler, useCapture) {
if (useCapture) {
throw "Browser doesn't support capturing phase";
}
this.attachEvent("on" + eventName, function() {
var e = window.event;
e.stopPropagation = stopPropagation;
e.preventDefault = preventDefault;
handler.call(this, e);
});
};
}
})();
Live Example | Source