编辑
我编写了一个代码片段,模拟了EventListener接口和ie8接口,可在普通对象上调用:
https://github.com/antcolag/iEventListener/blob/master/iEventListener.js
旧回答
这是一种在不支持addEventListener或attachEvent的浏览器上模拟它们的方法
希望能有所帮助
(function (w,d) {
var
nc = "", nu = "", nr = "", t,
a = "addEventListener",
n = a in w,
c = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","") ),
u = n?(nu = "attach", "add"):(nu = "add","attach"),
r = n?(nr = "detach","remove"):(nr = "remove","detach")
function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture() ) : capt ))}}
w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c)
w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c)
})(window, document)
if(element.addEventListener) {/*支持*/} else {/*不支持*/}
在所有浏览器中都是有效的,并且独立于实现方式。 - RobG