0

我正在编写一个小脚本来捕获键事件并轻松地在它们上绑定函数。但我现在被困住了!

问题是,如果我初始化多个“事件处理程序”,它会覆盖第一次初始化的参数。

千言万语不比几行代码多。所以,这是我到目前为止所做的:

var keyCodes={a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90,"0":48,"1":49,"2":50,"3":51,"4":52,"5":53,"6":54,"7":55,"8":56,"9":57,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,shift:16,ctrl:17,control:17,alt:18,option:18,opt:18,cmd:224,command:224,fn:255,"function":255,backspace:8,"delete":8,enter:13,"return":13,left:37,up:38,right:39,down:40};

var keyCall = function(k, fn, c, e, k2, nk) {
    this.onkeydown = function() {
        nk = k.split(" ");
        c = e ? e.which : event.keyCode;
        if (nk.length > 1) {
            if (keyCodes[nk[0]] === c) {
                k2 = true;
            }
            if (keyCodes[nk[1]] === c && k2 === true) {
                fn();
                k2 = false;
            }
        } else if (keyCodes[nk[0]] === c) {
            fn();
        }
    };
};


keyCall('ctrl a', function() { // overridden by `keyCall('shift a'`
    alert('callback1');
});

keyCall('shift a', function() {
    alert('callback2');
});

如果您认为带注释的版本很有用,我已经将其优化为极少的字节,那就直说吧!对于每个需要的人,这里有一个小提琴

更新

pascalfree 已修复它!但是现在又出现了一个问题……

“占位符”-变量k2检查第一个键是否被按下。但是现在,如果您按下并释放ctrl并随后点击-a键,该功能将被触发。有任何想法吗?

4

1 回答 1

1

我假设 onKeyPress 事件绑定到一些 html 元素,如下所示:

keyCall.apply( window.body, ['shift a', function() { alert('a') }] );

为了附加其他事件,您可以检查是否已定义事件处理程序并在新函数中调用它:

var keyCall = function(k, fn, c, e, k2, nk) {
    var oldOnkeydown = this.onkeydown; //get old event handler
    this.onkeydown = function() {
        if( typeof oldOnkeydown == "function" ) { oldOnkeydown() } //call in new eventhandler.
        nk = k.split(" ");
        c = e ? e.which : event.keyCode;
        if (nk.length > 1) {
            if (keyCodes[nk[0]] === c) {
                k2 = true;
            }
            if (keyCodes[nk[1]] === c && k2 === true) {
                fn();
                k2 = false;
            }
        } else if (keyCodes[nk[0]] === c) {
            fn();
        }
    };
    //reset k2 onkeyup
    var oldOnkeyup = this.onkeyup;
    this.onkeyup = function() {
      if( typeof oldOnkeyup == "function" ) { oldOnkeyup() }
      k2 = false;
    };
};

我只添加了带有注释的 2 行。(+最后的onkeyup事件以解决评论中的问题)

来源:http ://www.webreference.com/programming/javascript/onloads/index.html

于 2012-09-17T15:33:56.357 回答