简体   繁体   中英

Microsoft Edge - keydown event

I would like to switch between pages using arrows (37 - left arrow, 39 - right arrow). The code below works correctly with Firefox, Chrome and Internet Explorer.

The solution does not work with Microsoft Edge after Back (back in browsing history) button has been clicked in the browser. Does anybody know how to fix it?

<script type="text/javascript">

window.addEventListener("keydown", checkKeyPressed, false);

function checkKeyPressed(event) {

    var x = event.which || event.keyCode;

    if (x == 37) { window.location.href = "page1.html";}
    if (x == 39) { window.location.href = "page2.html";} 
};

</script>

This looks like a bug. In that when you use the navigation controls (or the refresh button) the window seems to lose focus and so keydown events do not fire. Also window.focus doesn't seem to work as expected either.

But I have found a workaround (or two). The first is to modify your script to look like this:

    <script>        
    window.onload = function(){
        document.body.focus();
        document.addEventListener("keydown", checkKeyPressed, false);

        function checkKeyPressed(event) {

            var x = event.which || event.keyCode;

            if (x == 37) { window.location.href = "page1.html"; }
            if (x == 39) { window.location.href = "page2.html"; }
        };            
    }
</script>

You then need to add a tab index to the body tag eg:

<body tabindex="1">

This then allows you to programmatically set the focus of the page (And it isn't ignored by Microsoft Edge like window.focus() is) The reason you need to add tabindex to the body is because the focus method is implicitly applicable to a limited set of elements, chiefly form and <a href> tags. In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property.

This workaround does add a potential accessibility issue since your element can gain focus via keyboard commands, such as the Tab key. Although I'm not sure how much of a problem that really is.

The second option is to add a form element to your page and either manually set focus to it or add the autofocus attribute:

 <input autofocus>

Edge seems to respect this and gives the element auto focus and your key down events will now fire. Sadly You can't just hide this element, since if it's hidden it no longer get auto focus. (maybe you could set it's opacity to 0) but I didn't try.

Of the two options I prefer workaround 1. I will file this as a bug with the Edge team on connect when I get a chance this afternoon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM