如果 html节点有 addEventListener 方法,这个怎么补呢
时间: 2024-01-10 14:42:13 浏览: 75
可以使用 polyfill(填充器)来实现,polyfill 通过在旧浏览器中添加缺失的方法、属性或 API 来实现新功能。对于缺少 addEventListener 方法的浏览器,可以使用以下 polyfill:
```
if (!Element.prototype.addEventListener) {
var eventListeners = [];
var addEventListener = function(type, listener /*, useCapture (will be ignored) */) {
var self = this;
var wrapper = function(e) {
e.target = e.srcElement;
e.currentTarget = self;
if (typeof listener.handleEvent != 'undefined') {
listener.handleEvent(e);
} else {
listener.call(self, e);
}
};
if (type == 'DOMContentLoaded') {
var wrapper2 = function(e) {
if (document.readyState == 'complete') {
wrapper(e);
}
};
document.attachEvent('onreadystatechange', wrapper2);
eventListeners.push({object: this, type: type, listener: listener, wrapper: wrapper2});
if (document.readyState == 'complete') {
var e = document.createEventObject();
// can't use dispatchEvent here because of bug 106133 in IE
// self.fireEvent('onreadystatechange', e);
wrapper2(e);
}
} else {
this.attachEvent('on' + type, wrapper);
eventListeners.push({object: this, type: type, listener: listener, wrapper: wrapper});
}
};
var removeEventListener = function(type, listener /*, useCapture (will be ignored) */) {
var counter = 0;
while (counter < eventListeners.length) {
var eventListener = eventListeners[counter];
if (eventListener.object == this && eventListener.type == type && eventListener.listener == listener) {
if (type == 'DOMContentLoaded') {
this.detachEvent('onreadystatechange', eventListener.wrapper);
} else {
this.detachEvent('on' + type, eventListener.wrapper);
}
eventListeners.splice(counter, 1);
break;
}
++counter;
}
};
Element.prototype.addEventListener = addEventListener;
Element.prototype.removeEventListener = removeEventListener;
if (HTMLDocument) {
HTMLDocument.prototype.addEventListener = addEventListener;
HTMLDocument.prototype.removeEventListener = removeEventListener;
}
if (Window) {
Window.prototype.addEventListener = addEventListener;
Window.prototype.removeEventListener = removeEventListener;
}
}
```
这个 polyfill 会为所有元素添加 addEventListener 和 removeEventListener 方法。如果浏览器支持 addEventListener,则这个 polyfill 不会对代码产生任何影响。如果浏览器不支持 addEventListener,则使用这个 polyfill 可以让代码在这些浏览器中正常工作。
阅读全文