简体   繁体   中英

Is it possible to prevent document scrolling when arrow keys are pressed?

Very straightforward:

Is it possible to prevent the browser from scrolling when a user pressed arrow keys?

yes. use something like: document.getElementById('yourID').onkeypress = HandleKeyPress;

function HandleKeyPress(e) {
    var e = e || window.event;
    switch (e.keyCode) {

        case e.DOM_VK_LEFT:
        case e.DOM_VK_RIGHT:
        case e.DOM_VK_UP:
        case e.DOM_VK_DOWN:
            if (e.preventDefault)
                e.preventDefault();
            else e.returnValue = false;
    }
}

Though it may not be a good idea to do so. just be sure that you're not overlooking a better approach.

Very straightforward: Yes, but don't do it.

Changing fundamental operation of how a browser operates just confuses or angers users, and makes the whole experience less user-friendly. The user should have ultimate control of the way his or her browser functions, not you. This is similar to blocking menu items from being accessed, or removing context menus etc.

It seems many are saying not to break what the browser does.

I would argue the same, unless you are replacing it with similar or better functionality.

I frequently kill the keyboard scroll in elements with an overflow because I've added a keyboard event to the element where using the keyboard "down" and "up" keys selects the items (think of a finder or windows explorer window).

The default scroll made the interaction all whacky. If the top item were selected, then you key 'down', it would select the next item but then scroll the element down and hide what was just selected.

So I break the default scroll, and then add my own to scroll to the selected item if it is below (or above) the current scrolling view. That way it behaves exactly as any OS out there when key-ing up and down through files.

Just saying, break it all you want, but make sure you know why you're breaking it and the user doesn't notice a thing.

在jQuery中,您可以执行以下操作:

$().keydown(function(e) { return e.keyCode != 38 && e.keyCode != 40; });

listen to the keydown event and prevent the default behavior.

In jquery

$(document).on('keydown.yournamespace', function(e) {e.preventDefault();});

可能吧,但是打破一个大家都知道和理解的约定通常不是一个好主意:D

在jQuery中

$("*").keypress(function(e){e.preventDefault(); return false;});

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