Javascript Internet Explorer 中的 addEventListener

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6927637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:48:16  来源:igfitidea点击:

addEventListener in Internet Explorer

javascriptinternet-explorerinternet-explorer-9addeventlistener

提问by The Mask

What is the equivalent to the Element Object in Internet Explorer 9?

Internet Explorer 9 中的元素对象等价于什么?

if (!Element.prototype.addEventListener) {
    Element.prototype.addEventListener = function() { .. } 
} 

How does it works in Internet Explorer?

它在 Internet Explorer 中是如何工作的?

If there's a function equal to addEventListenerand I don't know, explain please.

如果有一个函数等于addEventListener我不知道,请解释。

Any help would be appreciated. Feel free to suggest a completely different way of solving the problem.

任何帮助,将不胜感激。随意提出一种完全不同的解决问题的方法。

回答by user278064

addEventListeneris the proper DOM method to use for attaching event handlers.

addEventListener是用于附加事件处理程序的正确 DOM 方法。

Internet Explorer (up to version 8) used an alternate attachEventmethod.

Internet Explorer(最高版本 8)使用了另attachEvent一种方法。

Internet Explorer 9 supports the proper addEventListenermethod.

Internet Explorer 9 支持正确的addEventListener方法。

The following should be an attempt to write a cross-browser addEventfunction.

下面应该是尝试写一个跨浏览器的addEvent功能。

function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // W3C DOM
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE DOM
      elem.attachEvent("on"+evnt, func);
   }
   else { // No much to do
      elem["on"+evnt] = func;
   }
}

回答by jchook

John Resig, author of jQuery, submitted his version of cross-browser implementation of addEventand removeEventto circumvent compatibility issues with IE's improper or non-existent addEventListener.

约翰Resig的,jQuery的作者,他提交的跨浏览器实现的版本addEvent,并removeEvent与IE的不当或不存在规避的兼容性问题addEventListener

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}

Source: http://ejohn.org/projects/flexible-javascript-events/

资料来源:http: //ejohn.org/projects/flexible-javascript-events/

回答by RTeobaldo

I'm using this solution and works in IE8 or greater.

我正在使用此解决方案并在 IE8 或更高版本中工作。

if (typeof Element.prototype.addEventListener === 'undefined') {
    Element.prototype.addEventListener = function (e, callback) {
      e = 'on' + e;
      return this.attachEvent(e, callback);
    };
  }

And then:

进而:

<button class="click-me">Say Hello</button>

<script>
  document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
    console.log('Hello');
  });
</script>

This will work both IE8 and Chrome, Firefox, etc.

这将适用于 IE8 和 Chrome、Firefox 等。

回答by phtrivier

As Delan said, you want to use a combination of addEventListener for newer versions, and attachEvent for older ones.

正如 Delan 所说,您希望对较新版本使用 addEventListener 和对旧版本使用 attachEvent 的组合。

You'll find more information about event listeners on MDN. (Note there are some caveats with the value of 'this' in your listener).

您将在MDN上找到有关事件侦听器的更多信息。(请注意,在您的侦听器中,有一些带有“this”值的警告)。

You can also use a framework like jQueryto abstract the event handling altogether.

您还可以使用像jQuery这样的框架来完全抽象事件处理。

$("#someelementid").bind("click", function (event) {
   // etc... $(this) is whetver caused the event
});

回答by Eddie

Here's something for those who like beautiful code.

这是为那些喜欢漂亮代码的人准备的东西。

function addEventListener(obj,evt,func){
    if ('addEventListener' in window){
        obj.addEventListener(evt,func, false);
    } else if ('attachEvent' in window){//IE
        obj.attachEvent('on'+evt,func);
    }
}

Shamelessly stolen from Iframe-Resizer.

无耻地从Iframe-Resizer窃取。

回答by Delan Azabani

addEventListeneris supported from version 9 onwards; for older versions use the somewhat similar attachEventfunction.

addEventListener从版本 9 开始支持;对于旧版本使用有点类似的attachEvent功能。

回答by asdru

EDIT

编辑

I wrote a snippet that emulate the EventListener interface and the ie8 one, is callable even on plain objects: https://github.com/antcolag/iEventListener/blob/master/iEventListener.js

我写了一个模拟 EventListener 接口和 ie8 接口的代码段,即使在普通对象上也可以调用:https: //github.com/antcolag/iEventListener/blob/master/iEventListener.js

OLD ANSWER

旧答案

this is a way for emulate addEventListener or attachEvent on browsers that don't support one of those
hope will help

这是一种在不支持其中一个的浏览器上模拟 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")
/*
 * the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener"
 */
    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) // (add | attach)Event[Listener]
    w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener]

})(window, document)

回答by rofrol

I would use these polyfill https://github.com/WebReflection/ie8

我会使用这些 polyfill https://github.com/WebReflection/ie8

<!--[if IE 8]><script
  src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->