Pressing spacebar scrolls page down?

后端 未结 3 441
悲哀的现实
悲哀的现实 2020-11-30 10:56

I have a problem that I\'m not even sure what to search for in order to fix. When I press the spacebar my entire page moves up (scrolls down): I don\'t want this to happen.

相关标签:
3条回答
  • 2020-11-30 11:38

    The behavior you describe is pretty standard. If you are creating content that is taller than the page, why are you hiding some of it?

    0 讨论(0)
  • 2020-11-30 11:40

    It's not enough to just hide the overflow; you actually have to make it not overflow. Even if you could disable the behavior (eating the keystroke, putting focus inside some other container), the user might still be able to scroll via the keyboard, by drag-selecting text on the page, holding down the middle mouse button, etc... It's really up to their browser, and so long as the content is still technically visible, they'll probably have some way to scroll it into view.

    Time to re-think your layout.

    0 讨论(0)
  • 2020-11-30 11:49

    This default scrolling behavior comes from the keydown event. In order to prevent it, you must handle the keydown event and prevent the default behavior, either by returning false from the event handler or calling event.preventDefault().

    As a rule of thumb, think carefully before you prevent default behavior like spacebar scrolling. I use it all the time and I get extremely annoyed when it doesn't work in a page.

    But if you want to eat the key...

    window.onkeydown = function(e) {
        return e.keyCode !== 32;
    };
    

    According to the MDN web docs for KeyboardEvent#keyCode, keyCode is a deprecated property. Although it still works in most browsers, you are encouraged to use KeyboardEvent#key going forward, which is a more standardized string representation of a key. The key value for spacebar is literally the input value: " " (single space string). So if you wanted to be very careful to support all browsers, you could write:

    window.onkeydown = function(e) {
        return ev.keyCode !== 32 && ev.key !== " ";
    }
    
    0 讨论(0)
提交回复
热议问题