Drawing off the explanation provided in this example, I added the following code to my html as part of an immediately invoked function expression:

(function hideOverlayOnEsc(){
    document.addEventListener('keydown', function(e){
        if( e.keyCode == '27' ){
            cmnOverlayV2.hideOverlay();
        }
    }, false);

    // IE8 Fix
    if(!document.addEventListener){ 
        document.attachEvent("onkeydown", function(e){
            if( e.keyCode == '27' ){
                cmnOverlayV2.hideOverlay();
            }
        });
    }
})();

When these two versions of applying the event listener to the document are used separately, they work as intended. That is to say, that if the IE8 fix is removed, the code works properly in other browsers. And if the addEventListener code block is removed, it works properly in IE8. However, having both of these code blocks in place currently breaks the html in some way for at least one of the two browser categories (ie8 & not ie8)

Some additional information for reference:

The document object was used because the actual html element that should hide on Escape does not load into the DOM initially, and this was an easy way around that.

This code block functions properly (when one of the two inner code blocks are omitted) as either an inline <script> call or an external .js file's call.

The html in which this code block lives is injected into the DOM of another html document. In other words, what I am working with is just a part of the whole page that is added dynamically. Because of this, when I say the html is 'broken' what actually happens is the html I am editing is not present in the DOM of the parent html document.

I had considered setting up conditional comments to say something like <!--[if IE8]>USE SCRIPT B<![endif]--> but this is difficult because I do not have access to the <head> section of the parent html. I would prefer to just work this out within the hideOverlayOnEsc() function if possible.

有帮助吗?

解决方案

You have copied wrong. See carefully this answer. You code must be like this:

(function hideOverlayOnEsc(){
    // IE8 Fix
    if(document.addEventListener){ 
        document.addEventListener('keydown', function(e){
            if( e.keyCode == '27' ){
                cmnOverlayV2.hideOverlay();
            }
        }, false);
    } else {
        document.attachEvent("onkeydown", function(e){
            if( e.keyCode == '27' ){
                cmnOverlayV2.hideOverlay();
            }
        });
    }
})();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top