js 按键事件判断capslock是否开启

时间:2021-11-21 00:47:11

    最近有用到输入密码时检查 capslock 是否开启的一个检查,看了一些博客,发现有通过keyCode返回的值来做检查的,其实这种做法不对,在这里说下我的实现方法:

    首先看下keyCode对应的键值对:

   

keycode    8 = BackSpace BackSpace
keycode    9 = Tab Tab
keycode   12 = Clear
keycode   13 = Enter
keycode   16 = Shift_L
keycode   17 = Control_L
keycode   18 = Alt_L
keycode   19 = Pause
keycode   20 = Caps_Lock
keycode   27 = Escape Escape
keycode   32 = space space
keycode   33 = Prior
keycode   34 = Next
keycode   35 = End
keycode   36 = Home
keycode   37 = Left
keycode   38 = Up
keycode   39 = Right
keycode   40 = Down
keycode   41 = Select
keycode   42 = Print
keycode   43 = Execute
keycode   45 = Insert
keycode   46 = Delete
keycode   47 = Help
keycode   48 = 0 equal braceright
keycode   49 = 1 exclam onesuperior
keycode   50 = 2 quotedbl twosuperior
keycode   51 = 3 section threesuperior
keycode   52 = 4 dollar
keycode   53 = 5 percent
keycode   54 = 6 ampersand
keycode   55 = 7 slash braceleft
keycode   56 = 8 parenleft bracketleft
keycode   57 = 9 parenright bracketright
keycode   65 = a A
keycode   66 = b B
keycode   67 = c C
keycode   68 = d D
keycode   69 = e E 
keycode   70 = f F
keycode   71 = g G
keycode   72 = h H
keycode   73 = i I
keycode   74 = j J
keycode   75 = k K
keycode   76 = l L
keycode   77 = m M 
keycode   78 = n N
keycode   79 = o O
keycode   80 = p P
keycode   81 = q Q
keycode   82 = r R
keycode   83 = s S
keycode   84 = t T
keycode   85 = u U
keycode   86 = v V
keycode   87 = w W
keycode   88 = x X
keycode   89 = y Y
keycode   90 = z Z
对于同一个字母的大小写,keycode返回的值相同,所以通过检查 shift 键和keycode返回的值,是行不通的,后来查到函数 

charCodeAt() ,  该方法可返回指定位置的字符的 Unicode 编码 , 通过与shift键对于的keycode,就可以判断capslock是否开启了

function capslockonoff($input){
	$input.keyup(function(event){
		var e = event||window.event;
		var keyvalue = e.keyCode ? e.keyCode : e.which;
		var shifKey = e.shiftKey ? e.shiftKey:((keyvalue == 16) ? true : false);
		var strlen = $input.val().length;
		if(strlen){
			var uniCode = $input.val().charCodeAt($input.val().length-1);
			if(keyvalue>=65 && keyvalue<=90){     //如果是字母键
				if(((uniCode >= 65 && uniCode <= 90) && !shifKey)||((uniCode >= 97 && uniCode <= 122) && shifKey)){
					return true;  //开启
				}else{
					return false;  //未开启
				}
			}
		}
	});
}

参数是对应的输入框DOM对象