【问题标题】:Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection无法在“HTMLInputElement”上执行“setSelectionRange”:输入元素的类型(“数字”)不支持选择
【发布时间】:2016-01-29 02:51:10
【问题描述】:

当用户点击输入框时,我添加了下面的代码来选择整个文本:

<input type="number" onclick="this.setSelectionRange(0, this.value.length)" name="quantity" />

但我收到以下错误:

未捕获的 InvalidStateError:无法在“HTMLInputElement”上执行“setSelectionRange”:输入元素的类型(“数字”)不支持选择。

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

正如错误消息所说,您不能将setSelectionRange 与数字输入一起使用。如果您想使用 JavaScript 修改选择,则必须改用 &lt;input type="text"/&gt;

【讨论】:

  • 但我需要 type="Number" 用于平板电脑用户友好的目的(显示数字键盘)
  • 我明白这一点。很不幸。您必须选择其中一个。
  • @MehrdadBabaki 查看我的答案。
【解决方案2】:

evt.target.select() 在 Chrome 中选择 input type="number" 的内容,“if”结构在触摸设备上也是如此。

document.querySelector('.number_input').addEventListener('focus', function (evt) {
    evt.target.select();
    if ('ontouchstart' in window) {
      setTimeout(function() {
        evt.target.setSelectionRange(0, 9999);
      }, 1);
    }
}, true);

不幸的是,“如果”阻止了 Mac Safari 中的自动选择,我不知道如何在桌面浏览器和移动设备中获得相同的结果。

【讨论】:

    【解决方案3】:

    我在 Angular 1.5 中使用了一个漂亮的自定义指令(请参阅下面的打字稿示例)。

    由于在输入类型=“数字”时似乎无法以编程方式选择整个值,因此这里的策略是在编辑值时暂时将输入类型从数字更改为文本,然后将其更改回模糊的原始类型。

    这导致行为与本机行为略有不同,因为它实际上允许您在字段中输入“无效”数据。但是,在 blur 时,所有浏览器的本机号码验证逻辑都会启动并阻止提交任何无效数据。我敢肯定还有其他一些问题,但它在 Chrome 和 FireFox 中对我们来说已经足够好了,所以我想分享一下。

    /// Selects the entire input value on mouse click. 
    /// Works with number and email input types.
    export class SelectOnClick implements ng.IDirective {
        require = 'ngModel';
        restrict = 'A';
        private ogType: any
    
        constructor(private $window: ng.IWindowService) { }
    
        link = (scope: ng.IScope, element: any) => {
    
            element.on('click', () => {
                if (!this.$window.getSelection().toString()) {      
                    this.ogType = element[0].type;
                    element[0].type = 'text';
                    element[0].setSelectionRange(0, element[0].value.length);
                }
            })
    
            element.on('blur', () => {
                element[0].type = this.ogType;
            })
        }
    
        static factory(): ng.IDirectiveFactory {
            var directive = ($window: ng.IWindowService) => new SelectOnClick($window);
            directive['$inject'] = ['$window'];
            return directive;
        }
    } 
    

    【讨论】:

      【解决方案4】:

      请改用input type="tel"

      你的例子:

      <input type="tel" onclick="this.setSelectionRange(0, this.value.length)" name="quantity" />
      

      这样就可以解决问题并避免错误消息。

      在手机上,它会显示所需的数字键盘。

      【讨论】:

      • 不幸的是,键入 tel 并不能阻止字母输入
      【解决方案5】:

      我知道这是一个老问题,但我确实找到了一个很好的解决方法,而不使用 tel 输入类型。通过在选择之前将输入类型从number 更改为text,错误就会消失,您可以保留number 输入类型的所有好处。

      • tel 允许文本输入,这可能不适用于数字。
      • tel 不会在输入旁边显示数字“微调器”(仅当您需要时)。
      function onInputFocus(event) {
        const target = event.currentTarget;
      
        target.type = 'text';
        target.setSelectionRange(0, target.value.length);
        target.type = 'number';
      }
      

      【讨论】:

      • 不错!一个警告是,如果要在多个输入(一些文本和一些数字)上使用此函数,请确保仅在最后将 target.type 更改为数字,如果它是在开始时的那样。但是,很好的解决方案。
      • 在电子邮件类型上对我不起作用,一旦我将其设置回电子邮件,选择就会消失。
      【解决方案6】:

      作为Tri Q Tran's answer 的变体并使其更通用。这可能是更好的方法:

      const element = document.createElement('input');
      element.type = 'number';
      
      (function(originalFn){
          element.setSelectionRange = function() {
              this.type = 'text';
              originalFn.apply(this, arguments);
              this.type = 'number';
          }
      })(element.setSelectionRange);
      

      或者,如果您不介意污染原型,这是一个更通用的解决方案:

      (function(originalFn){
          HTMLInputElement.prototype.setSelectionRange = function() {
              if ( this.type === 'number' ) {
                  this.type = 'text';
                  originalFn.apply(this, arguments);
                  this.type = 'number';
              } else {
                  originalFn.apply(this, arguments);
              }
          }
      })(HTMLInputElement.prototype.setSelectionRange);
      

      【讨论】:

      • 该死的你的回答成功了,非常感谢你 :D !!
      【解决方案7】:

      输入type="number"不支持setSelectionRange

      您可以使用:type="text"inputmode="numeric",这将为移动用户显示数字键盘并支持setSelectionRange

          <input 
           type="text"
           inputmode="numeric"
           onclick="this.setSelectionRange(0, this.value.length)" 
           name="quantity" />
      

      【讨论】:

      • 这不显示向上/向下按钮,但对我有用。
      猜你喜欢
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 2020-12-18
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多