Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

html - Pressing spacebar scrolls page down?

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. My body tag is styled to overflow:hidden, if that has anything to do with it, so the page won't have any scrollbars. I'm usually pretty good at executing the preliminary troubleshooting techniques but in this case I don't even know where to start. How can I stop this behaviour?

Additional information: I am using jQuery 1.4.2

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 !== " ";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...