/*
不曉得有沒有人想過像 Konami 那種,按 "上上下下左右左右BA" 後,
會觸發某些事件的功能,如何撰寫,以下是我的實作,除了特定的 Konami 按鍵外,
也允許自訂自己的按鍵事件序列的測試方法,
整個程式的概念,是註冊 document 的 keyup 事件,並紀錄下最近 10 次的按鍵內容,
並提供一個 RegisterTest 方法,由註冊者自行決定目前按下的按鍵是否符合觸發的條件,
若符合要觸發什麼事件; RegisterTest 會先把這兩個 function 紀錄下來,
等到畫面上的 kepup 事件產生時,逐一呼叫 testFun , testFun 回傳 true ,
就呼叫 triggerFun 執行當初註冊的觸發事件。
這個程式需要 jQuery ,
另外這個陽春的版本不提供組合鍵的處理,當然稍微修改一下也可以支援組合鍵。
*/
var HotKeyControler = {
MAX_QUEUE: 10, /* 保留最後 10 個鍵盤事件 */
testFuns: new Object(),
triggerFuns: new Object(),
KeyQueue: new Array,
Keyup: function(event) {
HotKeyControler.KeyQueue.push(event.keyCode);
if (HotKeyControler.KeyQueue.length > HotKeyControler.MAX_QUEUE) {
HotKeyControler.KeyQueue.shift();
}
for (var key in HotKeyControler.testFuns) {
if (HotKeyControler.testFuns[key](event, HotKeyControler.KeyQueue)) {
HotKeyControler.triggerFuns[key]();
}
}
},
/* 函數名稱:註冊熱鍵
* 參數說明:(唯一鍵值, 測試function, 觸發function)
* 說 明:提供註冊熱鍵的方法,提供目前畫面被按下的按鍵佇列,供AP自行判斷是否觸發執行事件
*/
RegisterTest: function(key, testFun, triggerFun) {
if (typeof(testFun)=='function' && typeof(triggerFun)=='function') {
HotKeyControler.testFuns[key] = testFun;
HotKeyControler.triggerFuns[key] = triggerFun;
}
}
}
$(document).ready(function(){
$(document).unbind("keyup",HotKeyControler.Keyup);
$(document).bind("keyup",HotKeyControler.Keyup);
});
/* DEMO 註冊當按下 Konami(上上下下左右左右BA)時要觸發的事件 */
HotKeyControler.RegisterTest("Konami"
,function(event,code) { /* 上上下下左右左右BA */
if (code.length!=10) return false;
if (code[0]==38 && code[1]==38 && code[2]==40 && code[3]==40 &&
code[4]==37 && code[5]==39 && code[6]==37 && code[7]==39 &&
code[8]==66 && code[9]==65) {
return true;
}
return false;
}
,function() {
alert('上上下下左右左右BA!!!');
}
);
2012年8月21日
[Javascript] 實作熱鍵(HotKey)共用程式,以Konami(上上下下左右左右BA)為例
訂閱:
張貼留言
(
Atom
)
沒有留言 :
張貼留言