基于 jQuery 实现键盘事件监听控件

2020-05-17 06:27:43易采站长站整理

其中的

._setKeyComposition
是一个私有方法,用来写入自定义键盘事件的方法:


_setKeyComposition(config){
var altKey = config.alt;
var ctrlKey = config.ctrl;
var shiftKey = config.shift;
var threeKey = altKey && ctrlKey && shiftKey;
var ctrlAlt = altKey && ctrlKey;
var altShift = altKey && shiftKey;
var ctrlShift = shiftKey && ctrlKey;
var code = config.code + '';
if(threeKey){
this.keyTypeSet.threeKey[code] = config.type;
} else if(ctrlAlt) {
this.keyTypeSet.ctrlAlt[code] = config.type;
} else if(ctrlShift) {
this.keyTypeSet.ctrlShift[code] = config.type;
} else if(altShift) {
this.keyTypeSet.altShift[code] = config.type;
} else if(altKey) {
this.keyTypeSet.altKey[code] = config.type;
} else if(ctrlKey) {
this.keyTypeSet.ctrlKey[code] = config.type;
} else if(shiftKey) {
this.keyTypeSet.shiftKey[code] = config.type;
} else {
this.keyTypeSet.singleKey[code] = config.type;
}
return null;
};

这样,一个键盘事件监听控件就大功告成了,下面是完整实现代码:


/**
* @constructor 键盘事件监听器
* */
function KeyboardListener(param){
this._init(param);
}
!function(){
/**
* @private {String} param.ele 事件对象选择器
* */
KeyboardListener.prototype._init = function _init(param){
this.$ele = $(param.ele);
this._initEvents();
this._initEventType();
return null;
};
/**
* @private _emptyEventHandler 空白事件响应
* */
KeyboardListener.prototype._emptyEventHandler = function _emptyEventHandler(){
return null;
};
/**
* @private _initEventType 初始化所有初始自定义事件类型
* */
KeyboardListener.prototype._initEventType = function _initEventType(){
var allType = ['up', 'down', 'left', 'right', 'undo', 'redo', 'zoomIn', 'zoomOut', 'delete'];
var intLen = allType.length;
this.allEventType = allType;
this.callback = {};
this.eventDiscibeSet = {};
for(var intCnt = 0; intCnt < intLen; intCnt++){
this.callback['on' + allType[intCnt]] = KeyboardListener.prototype._emptyEventHandler;
}
return null;
};
/**
* @private _initEvents 绑定 DOM 事件
* */
KeyboardListener.prototype._initEvents = function _initEvents(){
var $ele = this.$ele;
$ele.attr('tabindex', 1);
$ele.on('mouseenter', function(){
$ele.focus();
});
$ele.on('keydown', this._keyDownHandler.bind(this));