你如何告诉如果大写锁定使用JavaScript?
但有一个警告:我做了谷歌,我能找到的最好的解决方案是附加一个onkeypress事件到每个输入,然后检查每次按下的字母是否大写,如果是,然后检查shift是否也按下。如果不是,那么caps lock必须是打开的。这感觉真的很脏,而且…浪费——肯定有比这更好的办法吗?
你如何告诉如果大写锁定使用JavaScript?
但有一个警告:我做了谷歌,我能找到的最好的解决方案是附加一个onkeypress事件到每个输入,然后检查每次按下的字母是否大写,如果是,然后检查shift是否也按下。如果不是,那么caps lock必须是打开的。这感觉真的很脏,而且…浪费——肯定有比这更好的办法吗?
当前回答
在下面的代码,它将显示警报时,Caps锁定,他们按下键使用shift。
如果返回false;那么当前字符将不会附加到文本页。
$('#password').keypress(function(e) {
// e.keyCode is not work in FF, SO, it will
// automatically get the value of e.which.
var s = String.fromCharCode( e.keyCode || e.which );
if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
alert('caps is on');
return false;
}
else if ( s.toUpperCase() !== s) {
alert('caps is on and Shiftkey pressed');
return false;
}
});
其他回答
我写了一个名为capsLock的库,它完全是你想要它做的。
只要把它包括在你的网页上:
<script src="https://rawgit.com/aaditmshah/capsLock/master/capsLock.js"></script>
然后像这样使用它:
alert(capsLock.status);
capsLock.observe(function (status) {
alert(status);
});
参见演示:http://jsfiddle.net/3EXMd/
按下“Caps Lock”键更新状态。它只使用Shift键来确定Caps Lock键的正确状态。最初状态为false。所以要小心。
最近在hashcode.com上有一个类似的问题,我创建了一个jQuery插件来处理它。它还支持对数字的大写锁定识别。(在标准德语键盘布局上,大写锁定对数字有影响)。
你可以在这里查看最新版本:jquery.capsChecker
这段代码检测大小写锁定,无论是否按下shift键:
$('#password').keypress(function(e) {
var s = String.fromCharCode( e.which );
if ( (s.toUpperCase() === s && !e.shiftKey) ||
(s.toLowerCase() === s && e.shiftKey) ) {
alert('caps is on');
}
});
反应
onKeyPress(event) {
let self = this;
self.setState({
capsLock: isCapsLockOn(self, event)
});
}
onKeyUp(event) {
let self = this;
let key = event.key;
if( key === 'Shift') {
self.shift = false;
}
}
<div>
<input name={this.props.name} onKeyDown={(e)=>this.onKeyPress(e)} onKeyUp={(e)=>this.onKeyUp(e)} onChange={this.props.onChange}/>
{this.capsLockAlert()}
</div>
function isCapsLockOn(component, event) {
let key = event.key;
let keyCode = event.keyCode;
component.lastKeyPressed = key;
if( key === 'Shift') {
component.shift = true;
}
if (key === 'CapsLock') {
let newCapsLockState = !component.state.capsLock;
component.caps = newCapsLockState;
return newCapsLockState;
} else {
if ((component.lastKeyPressed !== 'Shift' && (key === key.toUpperCase() && (keyCode >= 65 && keyCode <= 90)) && !component.shift) || component.caps ) {
component.caps = true;
return true;
} else {
component.caps = false;
return false;
}
}
}
在jQuery中,
$('#example').keypress(function(e) {
var s = String.fromCharCode( e.which );
if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
alert('caps is on');
}
});
避免类似退格键的错误,需要s. tolowercase () !== s。