Once disable arrow key scrolling in users browser,

2019-06-08 18:41发布

Disable arrow key scrolling in users browser Zeta was given correct answer for how to disable the arrow keys.

I need to re-enable arrow key navigation once its disabled.

$('main navigation').has('drop down').bind('keyup', function (e) {
    if (e.keyCode == 40) {hover(e,$(this));} //Down Arrow Key press, how mega menu
    if (e.keyCode == 38) {unhover(e);} //Up Arrow Key Press, hide mega menu
    if (e.keyCode == 9) {checkTab();} //check if tab pressed
}

var checkTab = function (){
        // i check, if tab focus to the main menu anchor
    if($('main navigation').is(':focus')){
        var keys = [];
        window.addEventListener("keydown",
            function(e){
                keys[e.keyCode] = true;
                switch(e.keyCode){
                    case 37: case 39: case 38:  case 40: // Arrow keys
                    case 32: e.preventDefault(); break; // Space
                    default: break; // do not block other keys
                }
            },
        false);
        window.addEventListener('keyup',
            function(e){
                keys[e.keyCode] = false;
            },
        false);             
        console.log('focused')
    }
    else {
        console.log('f out')    
    }                   
}

this works fine, but as I have bind window.event to disable. once disabled I cant enable. Need help in this point.

2条回答
啃猪蹄的小仙女
2楼-- · 2019-06-08 19:17

Use another variable to determine whether you should currently block the arrow keys:

var useArrowKeysToScroll = false;

/* ... */
function(e){
    keys[e.keyCode] = true;
    if(!useArrowKeysToScroll && 
           ((e.keyCode >= 37 && e.keyCode <= 40) || 
             e.keyCode == 32)){
        e.preventDefault();
    }
    /* handle other keys etc... */
}, /* ... */

If useArrowKeysToScroll is false it the arrow keys and space bars won't result in scrolling.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-06-08 19:19

You can use use Jquery on/off to solve this..

First attach the keydown like so..

$('window').on('keydown', function(){
        //Your Function Here
        });

Then to detach, do this...

$('window').off('keydown');
查看更多
登录 后发表回答