【问题标题】:shiftKey in Safari on iOSiOS 上 Safari 中的 shiftKey
【发布时间】:2012-07-11 15:42:44
【问题描述】:

有没有办法在javascript中确定是否在移动键盘上按下了shift键,并将其与大写锁定(两次按下shift键)区分开来

【问题讨论】:

  • 这似乎是个老问题:stackoverflow.com/q/4555006/561731
  • 您需要通过iOS SDK还是通过网站处理?
  • @MatrosovAlexander 我是假设一个网站。
  • this fiddle 中使用我的 iPod 4.3,根本没有检测到 shift 键。

标签: javascript ios safari


【解决方案1】:

一些事实

首先,让我们看一些关于 iOS 键盘的事实,我想你已经知道了:

  • 当您进入键盘模式时,shift 键始终处于激活状态
  • Caps Lock 必须手动激活(估计这个用的不是太广)

iPhone Shift 键处理

我对此问题进行了一些调查,结果如下:

  • shift 键触发无键事件

  • 没有特殊的 iPhone 浏览器 API 来检测是否按下了 shift 键,除了在 iOS 应用程序中(duh)

  • iOS 触发的keydownkeypresskeyup 事件看起来很正常,只是它们不指示 shiftKey 的使用,除了它们的时间戳和类型之外无法区分。

    李>
  • 由于this issuekeyCodewhich 是只读的并且始终设置为0,因此您无法在iOS 中手动调度键盘事件。重新触发键盘事件以获取有关 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 键,这不是一个解决方案。这在现在看来是不可能的。

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2021-03-30
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多