如何使用<input type ="number"/>字段克服WhatWG/W3C/Chrome版本33.0.1750.146"回归错误"

scu*_*ffe 11 javascript w3c google-chrome html-input soft-keyboard

我在引号中加上"回归错误"这个词,因为这显然有一些不一致的意见.有关详细信息,请访问Bugzilla中的Bug 24796.

简而言之,Google Chrome根据最新版本的WhatWG规范实施了更改:http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type- attr-summary从字段 中删除了以下属性和方法<input type="number"/>.

属性:

  • selectionStart
  • 选定结束

方法:

  • 选择()
  • setSelectionRange(开始,结束)

(还有其他但这些是常用的关键)

如果您检查HTMLInputElement尝试调用方法的"数字"实例或请求属性将引发异常,则定义方法.:-(

恕我直言这是一个错误(因为功能已被删除,没有任何收获......并且有1,000个网站/应用程序通过JavaScript为这些数字输入字段提供扩展行为......但我离题了(对于那些希望要解决它请使用上面列出的bug帖子))

TL; DR

出于可用性目的,我当然希望并计划继续使用<input type="number"/>字段,因为它们向用户代理提供"提示",如果在移动设备(智能手机/平板电脑/?)上,我希望在字段为时显示数字键盘专注于默认的alpha键盘.

但是对于当前版本的Chrome(版本33.0.1750.146)和盲目实现此规范更改的任何其他浏览器,我想安全地将渲染字段转换回 <input type="text"/>

笔记:

  • 在修改其内容时尝试动态更改这些字段已证明是不成功的,因为字段在更改type属性时会丢失其选择范围.
  • 我确实有一个我想出的解决方案,我很快就会发布,但我想确保这个问题/答案适用于遇到此问题的所有开发人员

scu*_*ffe 4

我已经用以下代码解决了这个问题:

function checkForInputTypeNumberBug(){
  var dummy = document.createElement('input');
  try {
    dummy.type = 'number';
  } catch(ex){
    //Older IE versions will fail to set the type
  }
  if(typeof(dummy.setSelectionRange) != 'undefined' && typeof(dummy.createTextRange) == 'undefined'){
    //Chrome, Firefox, Safari, Opera only!
    try {
      var sel = dummy.setSelectionRange(0,0);
    } catch(ex){
      //This exception is currently thrown in Chrome v33.0.1750.146 as they have removed support
      //for this method on number fields. Thus we need to revert all number fields to text fields.
      $('input[type=number]').each(function(){
        this.type = 'text';
      });
    }
  }
}
$(document).ready(function(){
  checkForInputTypeNumberBug();
});
Run Code Online (Sandbox Code Playgroud)

我将其设为独立函数,因为在某些情况下,字段是通过 AJAX 加载的,并且我需要能够动态调用该函数。

此代码处理较旧的 IE 版本,其中尝试设置类型将失败,并处理 Chrome 中的异常(在虚拟元素上),以便页面可以克服此行为更改。

更新:根据 @Andy E 关于使用 inputmode 属性的建议(当前不受支持),我创建了一个错误,尝试在用户代理删除选择 API 之前优先考虑 inputmode 的实现:https://www.w3.org/Bugs /Public/show_bug.cgi?id=26695