简体   繁体   中英

Prevent space and arrow keys scrolling web page?

I am overriding the behavior of the space bar and arrow keys when an element is focused to provide keyboard support on a web page. I need to disable the default behavior of those keys, which is to scroll the web page. I thought all that was needed to do this was to return false when you handled the event, but that didn't do the trick. I also added preventDefault yet it still scrolls the page in addition to performing my custom actions. What is the problem here?

document.getElementById('someID').onkeyup = function(e) {
    var keyCode = e.which || e.keyCode;
    var handled = false;

    if (keyCode == 38 || keyCode == 40) { //up or down arrow
        //do something fun
        e.preventDefault();
        handled = true;
    }

    return !handled; //return false if the event was handled
}

Change the event to onkeydown . By the time you reach onkeyup it's too late and the scrolling has already changed.

document.getElementById('someID').onkeydown = function(e) {
    var keyCode = e.which || e.keyCode;
    var handled = false;

    if (keyCode == 38 || keyCode == 40) { //up or down arrow
        //do something fun
        e.preventDefault();
        handled = true;
    }

    return !handled; //return false if the event was handled
}

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