通过javascript禁用和启用箭头键 [英] Disable and Enable Arrowkeys by javascript

查看:76
本文介绍了通过javascript禁用和启用箭头键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,首先我需要禁用键盘箭头键,然后再进行一些处理启用它,为此我写了这个jquery函数

I have a scenario where first I need to disable keyboard arrow keys and after some processing again Enable it,for this I write this jquery function

function DisableArrowKeys() {
        var ar = new Array(37, 38, 39, 40);
        $(document).keydown(function(e) {
            var key = e.which;
            if ($.inArray(key, ar) > -1) {
                e.preventDefault();
                return false; 
           }
            return true;
        });
    }

此功能可以禁用箭头键,经过一些处理我需要启用箭头键为此我在下面的函数中进行了更改

this function can disable arrow keys,after some processing I need to enable arrow key for this I made changes in the function like below

function EnableArrowKeys() {
        var ar = new Array(37, 38, 39, 40);
        $(document).keydown(function(e) {
            var key = e.which;
            if ($.inArray(key, ar) > -1) {              
                return true;
            }           
        });
    }

但是当我们调用该函数时,它不会启用箭头键。

But when we call that function it does not enable arrowkeys.

推荐答案

您需要保留对禁用功能的引用,并在准备好再次接受箭头键时取消绑定。类似于:

You need to keep a reference to your disabling function, and unbind it when you are ready to accept arrow keys once more. Something like:

var ar = new Array(37, 38, 39, 40);
var disableArrowKeys = function(e) {
    if ($.inArray(e.keyCode, ar)>=0) {
        e.preventDefault();
    }
}

$(document).keydown(disableArrowKeys);

// then when you are ready to enable, unbind the function...
$(document).unbind('keydown', disableArrowKeys);

这篇关于通过javascript禁用和启用箭头键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆