Will this JavaScript code affect other keypress events too by disabling one key?

浪尽此生 提交于 2019-12-12 17:35:40

问题


I'm using this to disable the 'scrolling' effect the spacebar has in a browser. Will this affect other keypress events too?

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

Could someone please explain what this is doing? I'm not sure if this code is bad, but it seems to disable other keypress related codes in my page, and I want to make sure this isn't the reason.

Thanks!


回答1:


ASCII code 32 is the ASCII value that represents the spacebar key, and your code is essentially telling the browser to return false whenever that keycode is detected. Since false is returned, the scrollbar effect you speak of is in fact successfully disabled.

However, the unfortunate side effect of this convenient spacebar-scroll-disabling function is that it disables spacebar keypresses everywhere on the page.

Instead of returning false, if the keycode is detected, pass the current scrollTop value into a closure that returns a function to a setTimeout event. When the setTimeout fires, the scrollTop position is reset back to the value it was in when the setTimeout event was first registered.

window.onkeydown = function(e) {
    if(event.keyCode == 32) { // alert($(document).scrollTop() );
        setTimeout(                 
            (function(scrollval) { 
                return function() { 
                    $(document).scrollTop(scrollval);
                };
            })( $(document).scrollTop() ), 0);
    }
};

Your users can still conveniently make use of spacebars in input textboxes and textareas, and at the same time, pressing the spacebar key while not focused on a text element will no longer result in the page scrolling.

Under the hood, the scroll is still taking place. It's just being reset at a rate fast enough to where the user doesn't notice.

If you increase this value to 100 or 1000, it will give you a better idea of what is going on under the hood. You'll actually see the page scroll and then get set back to the previous scroll position.

This was only tested in Chrome and Firefox 13! So you may have to adjust the setTimeout duration -- currently 0 -- to a different value in browsers like Internet Explorer. Be prepared to gracefully degrade -- by supporting this feature only in modern browsers -- if necessary.

UPDATE:

For reference, below is the method to use to make this compatible in the major browsers. It has been tested in Chrome, Firefox, IE8, IE9, and Safari.

While it does work in IE8/IE9, it isn't very smooth.

// put the eventhandler in a named function so it can be easily assigned
   // to other events.
function noScrollEvent(e) {
    e = e || window.event;
    if(e.keyCode == 32) {  
        setTimeout(                 
            (function(scrollval) { 
                return function() { 
                    $(document).scrollTop(scrollval);
                };
            })( $(document).scrollTop() ), 0);
    }
}


// Chrome and Firefox must use onkeydown
window.onkeydown = noScrollEvent;

// Internet Explorer 8 and 9 and Safari must use onkeypress
window.document.onkeypress = noScrollEvent;



回答2:


If another element is bound to the keydown event it will not be effected by this code

See my fiddle and try adding and remove the textarea listening to the keydown event

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

document.getElementsByTagName("textarea")[0].onkeydown = function(e) {
    alert("hi");
}

http://jsfiddle.net/HnD4Y/




回答3:


The answer above with the setTimeout did not work for me at all on Chome with a delay of 0. With a delay bumped above 50ms, it began to work, but that caused a noticeable page jump. I believe that setTimeout was scrolling the page up too early, then Chrome moved it down later.

Below is my solution that is working well. It returns false on the keydown event to prevent the browser from doing a page-down. Then you make sure event you set up on your button etc. to use the keyup event instead.

$(mySelector).keyup(eventHandlerFunction);

[dom element].onkeydown = function(event) {
  if (event.keyCode == 32) {return false;}
};

Note: input fields will not reflect spacebar key events if they or their parent are covered by this onkeydown handler



来源:https://stackoverflow.com/questions/10661296/will-this-javascript-code-affect-other-keypress-events-too-by-disabling-one-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!