【问题标题】:Disable and Enable Arrowkeys by javascript通过 javascript 禁用和启用箭头键
【发布时间】:2011-09-19 07:21:24
【问题描述】:

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

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;
        });
    }

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

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;
            }           
        });
    }

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

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

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

    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);
    

    【讨论】:

      【解决方案2】:

      第二个处理程序(附加在EnableArrowKeys 函数中)没有取消第一个处理程序。 jQuery 事件处理程序是链式的:

      If there are multiple handlers registered, they will always execute in the order in which they were bound.

      所以,在EnableArrowKeys 函数中使用unbind 函数,而不是添加另一个处理程序。

      function EnableArrowKeys() {
          $(document).unbind('keydown');
      }
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        var DisableArrowKeys = function(e){
            if ($.inArray(e.which, ar) > -1) {
                e.preventDefault();
                return false; 
            }
            return true;
        }
        $(document).bind("keydown", DisableArrowKeys);
        

        然后解除绑定:

        $(document).unbind("keydown", DisableArrowKeys);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多