22

<input>属性autocapitalize="words"在 iOS 8,9 下使用默认 iOS 键盘的移动 Safari 中被破坏。它将字段的前 2 个字母大写,而不是每个单词的第一个字母。

官方文档说支持:https ://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html

要进行测试,请在 iOS 模拟器或真机上打开以下字段:

First name: <input type="text" autocorrect="off" autocapitalize="words" value="First Name">

您可以使用https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_form_submit进行测试,或者在 iOS 8 或 9 上使用此代码段:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Test autocapitalize</title>
   </head>
  <body>
    <form>
      <label for="words">autocapitalize="words"</label>
      <input type="text" autocapitalize="words" name="text1" id="words" /><br />
      <label for="sentences">autocapitalize="sentences"</label>
      <input type="text" autocapitalize="sentences" name="text2" id="sentences" /><br />
      <label for="none">autocapitalize="none"</label>
      <input type="text" autocapitalize="none" name="text3" id="none" />
    </form>
  </body>
</html>

我很惊讶这从 8.x 开始就已经存在并且已经被忽视了。

有已知的解决方法吗?

10/13 更新:iPhone 6s+ Safari 完全忽略输入字段上设置的任何 HTML 属性。

4

1 回答 1

1

如果您愿意(暂时)包含此库,则似乎有解决此问题的方法:https ://github.com/agrublev/autocapitalize 。然而,它确实需要 jQuery,因此在移动设备上可能并不理想。我创建了一小段代码,它在不使用 jQuery 的情况下只为单词做同样的事情。当然也可以扩展到包括其他情况。

下面的示例还将最初在 page ready 上的单词大写,而不仅仅是在 'keyup' 事件上。我已经在几台设备上测试了代码,但没有出现错误。但是,如果某些事情不起作用或者您觉得可以做得更好,请随时发表评论。

请注意,我添加的“domReady”功能适用于 IE9 及更高版本。如果您需要对旧版本的支持,请参阅此内容。

// Create one global variable
var lib = {};

(function ( lib ) {

  lib.autocapitalize_element = function (element) {
    var val = element.value.toLowerCase();
    var split_identifier = " ";
    var split = val.split(split_identifier);
    for (var i = 0; i < split.length; i ++) {
      var v = split[i];
      if ( v.length ) {
          split[i] = v.charAt(0).toUpperCase() + v.substring(1);
      }
    };
    val = split.join(split_identifier);
    element.value = val;
  }

  lib.autocapitalize_helper = function(element) {
    element.onkeyup = function(e) {
      var inp = String.fromCharCode(e.keyCode);
      if (/[a-zA-Z0-9-_ ]/.test(inp)) {
        lib.autocapitalize_element(element);
      }
    };
  }

  lib.autocapitalize = function() {
    var elements = document.querySelectorAll("input[autocapitalize], textarea[autocapitalize]");
    for(var i = 0; i < elements.length; i++) {
      lib.autocapitalize_helper(elements[i]);
      lib.autocapitalize_element(elements[i]);
    }
  }

  lib.domReady = function(callback) {
    document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
  };
}( lib ));


// This function gets called when the dom is ready. I've added it to the lib variable now because I dislike adding global variables, but you can put it anywhere you like.
lib.domReady(function() {
  lib.autocapitalize();
});
于 2017-07-12T15:09:44.107 回答