码迷,mamicode.com
首页 > Web开发 > 详细

自制简易jquery键盘监听插件

时间:2014-12-29 16:59:39      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
/**
 * 简易键盘监听事件
 * @author shine.s
 */
var KeyListener = (function(){
	var _debug = false;
	var _ups = {};
	var _mods = {
		‘shift‘: ‘shiftKey‘,
		‘ctrl‘: ‘ctrlKey‘,
		‘alt‘: ‘altKey‘,	
	}
	var KEYS = {
			‘backspace‘: 8,
	        ‘tab‘: 9,
	        ‘enter‘: 13, ‘return‘: 13,
	        ‘pause‘: 19,
	        ‘caps‘: 20, ‘capslock‘: 20,
	        ‘escape‘: 27, ‘esc‘: 27,
	        ‘space‘: 32,
	        ‘pgup‘: 33, ‘pageup‘: 33,
	        ‘pgdown‘: 34, ‘pagedown‘: 34,
	        ‘end‘: 35,
	        ‘home‘: 36,
	        ‘ins‘: 45, ‘insert‘: 45,
	        ‘del‘: 46, ‘delete‘: 46,

	        ‘left‘: 37,
	        ‘up‘: 38,
	        ‘right‘: 39,
	        ‘down‘: 40,

	        ‘*‘: 106,
	        ‘+‘: 107, ‘plus‘: 107,
	        ‘-‘: 109, ‘minus‘: 109,
	        ‘;‘: 186,
	        ‘=‘: 187,
	        ‘,‘: 188,
	        ‘.‘: 190,
	        ‘/‘: 191,
	        ‘`‘: 192,
	        ‘[‘: 219,
	        ‘\\‘: 220,
	        ‘]‘: 221,
	        "‘": 222
	}
	var i;
    //小键盘
    for (i = 0; i < 10; i++) {
        KEYS[‘num-‘ + i] = i + 96;
    }
    //数字
    for (i = 0; i < 10; i++) {
        KEYS[i.toString()] = i + 48;
    }
    // f1-f24
    for (i = 1; i < 25; i++) {
        KEYS[‘f‘ + i] = i + 111;
    }
    //字母
    for (i = 65; i < 91; i++) {
        KEYS[String.fromCharCode(i).toLowerCase()] = i;
    }
	
	function addListener(keycode, callBack) {
		if(typeof(keycode) == ‘object‘) {
			$.each(keycode, function(k,v){
				_ups[k] = v;
			})
		} else {
			_ups[keycode] = callBack;
		}
	}
	
	function proccess(e) {
		keycode = e.which ? e.which : e.keyCode;
		if(_debug) {
			console.log("Now: "+keycode);
		}
		$.each(_ups, function(k,v) {
			var kArr = k.split(‘+‘);
			flag = true;
			if(kArr.length>1) {
				for(var i=0; i<kArr.length-1; i++) {
					var spec = kArr[i];
					if(_mods[spec]) {
						var flag = flag && e[_mods[spec]];
					}
				}
				var k = kArr[kArr.length-1];
			}
			if(KEYS[k] == ‘undefined‘) {
				return true;
			}
			if(flag && keycode == KEYS[k]) {
				return v();
			}
		})
	}

	if(_ups) {
		$(document).keyup(proccess);
	}
	
	function debug() {
		_debug = true;
	}
	
	return {
		debug: debug,
		addListener: addListener,
	};
})();

//test-demo
$(function(){
	KeyListener.addListener(‘c‘, c);
	KeyListener.addListener({
		‘left‘: left,
		‘right‘: function(){
			right(1, 6);
		},
		‘shift+alt+f‘: d,
		‘shift+e‘: e,
	});
	function left() {
		console.log(‘test‘);
	}
	function right(a, b) {
		console.log(a+b);
	}
	function c() {
		console.log(‘c‘);
	}
	function d() {
		console.log(‘D‘);
	}
	function e() {
		console.log(‘e‘);
	}
})
</script>



自制简易jquery键盘监听插件

标签:

原文地址:http://my.oschina.net/u/948242/blog/361952

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!