attachEvent Doesn't work in IE > 8.0

前端 未结 1 857
天涯浪人
天涯浪人 2021-02-05 21:44

I\'m using attachEvent for a while, but it seems that IE doesn\'t support this anymore?

window.attachEvent(\"onload\",Start_Wysiwyg);
window.attachEvent(\"onscro         


        
相关标签:
1条回答
  • 2021-02-05 21:51

    .attachEvent() is deprecated in IE9+, and has been removed in IE11.

    The standard is .addEventListener() (MSDN docs). The MDN docs have a section about compatibility.

    You can simply run some feature-checking code to check if the supported features exist:

    if (window.addEventListener) {
        // Check for addEventListener first, since IE9/10 have both,
        // but you should use the standard over the deprecated IE-specific one
        window.addEventListener('click', myFunc);
    } else if (window.attachEvent) {
        window.attachEvent('onclick', myFunc);
    }
    

    If you have to attach a lot of event listeners, then you may want to just cache the desired listener attachment method in a variable and use that variable for attaching your events throughout your code, rather than having that above check for every single event listener:

    var addListener = function(){}; // Default to no-op function
    
    if (window.addEventListener) {
        addListener = window.addEventListener;
    } else if (window.attachEvent) {
        addListener = function(eventType, listener, useCapture) {
            // attachEvent wants 'oneventType' instead of 'eventType'
            window.attachEvent('on'+eventType, listener, useCapture);
        };
    }
    
    // Now you can add listeners with a browser-agnostic function call!
    addListener('click', myFunc);
    addListener('hover', myOtherFunc);
    

    You can read more in a duplicate question linked by @MartyIX in a comment on your question. There are further nuances and methods in the answers/comments there, such as IE9 requiring <!DOCTYPE html> in order to use .addEventListener().

    0 讨论(0)
提交回复
热议问题