有没有办法在javascript中判断是否按下了移动键盘上的shift键,并将其与大写锁定(两次按下shift键)区分开来
最佳答案
一些事实
首先,让我们看一下我假设您已经知道的有关 iOS 键盘的一些事实:
- 当您进入键盘模式时,
shift
键始终处于激活状态 Caps Lock
必须手动激活(我猜这个用的不多)
iPhone Shift 键处理
我对这个问题进行了一些调查,这是我的发现:
shift
键触发无键事件没有专门的 iPhone 浏览器 API 来检测是否按下了 shift 键,除了在 iOS 应用程序中(duh)
iOS 触发的
keydown
、keypress
、keyup
事件看起来很正常,除了它们不表示 shiftKey 用法,而且除了从他们的时间戳和类型无法区分。由于 this issue,您无法在 iOS 中手动发送键盘事件,
keyCode
和which
是只读的并且总是设置为0
。重新触发键盘事件以获取有关 shift 键仍处于打开状态的指示是不可能的。实际上,iPhone 将
shift
键视为某种Short Term Caps Lock
键。不同的是,通常情况下,您激活它一次,它就会自动停用。
可以做什么
我假设您想在输入字段上指示用户是否应该小心按下 Shift/Caps Lock(例如密码字段)。我想到的是某种解决方法,但我认为总比没有好。
You can also test the jsfiddle here .
DOM 设置
<div id="wrapper">
<label for="test">ENTER SOMETHING HERE</label>
<input type="text" name="test" id="test"/>
</div>
<div id="warning"></div>
Javascript
这会检查用户是否确实输入了大写输入,如果输入了两个大写字母,它会假定用户正在使用 caps lock
。
var isCaps = false,
isUppercase = false,
str = '',
test = document.getElementById('test'),
warning = document.getElementById('warning');
function capsDetection(e) {
// Since where on iOS, we at least don't have to care
// about cross-browser stuff
var s = String.fromCharCode(e.which);
isCaps = isUppercase;
// if the char doesn't match its lower case friend, and the shift key is
// not pressed (which is always the case on iOS, but we leave it there
// for readability), we have uppercase input
isUppercase = (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey);
// if its the second uppercase input in a row, we may have caps lock input
isCaps = isCaps && isUppercase;
// set the warning
if (isUppercase && !isCaps) {
str = 'You where using the shift key';
}
else if (isCaps) {
str = 'Caps lock seems to be activated';
} else {
str = '';
}
warning.innerHTML = str;
}
// the right event properties are only available on keypress
test.addEventListener('keypress', capsDetection);
正如我所说,总比没有好,但如果您需要知道按下 shift 键而用户不进行任何输入,则不是解决方案。现在这似乎是不可能的。
关于javascript - iOS 上 Safari 中的 shiftKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11436366/