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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33406169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:01:32  来源:igfitidea点击:

Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection

javascriptjqueryhtmlcss

提问by Mehrdad Babaki

I added the code below to select whole text when user click on input box:

我添加了以下代码以在用户单击输入框时选择整个文本:

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

But I receive the error below:

但我收到以下错误:

Uncaught InvalidStateError: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection.

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

采纳答案by Kai Noack

Use input type="tel"instead.

使用input type="tel"来代替。

For your example:

对于您的示例:

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

That will do the trick and avoid the error message.

这将解决问题并避免错误消息。

And on mobile phones, it shows up the desired number pad.

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

回答by Tri Q Tran

I know this is an old question, but I did find a good workaround without using the telinput type. By changing the input type from numberto textbefore the selection, the error goes away and you get to keep all the benefits of the numberinput type.

我知道这是一个老问题,但我确实找到了一个不使用tel输入类型的好方法。通过更改输入类型numbertext选择之前,错误消失,你会得到保留的所有优点number输入类型。

  • telallows text input, which may not work with numbers.
  • teldoes not show the number "spinner" next to the input (only if you want it).
  • tel允许文本输入,这可能不适用于数字。
  • tel不会在输入旁边显示数字“微调器”(仅当您需要时)。
function onInputFocus(event) {
  const target = event.currentTarget;

  target.type = 'text';
  target.setSelectionRange(0, target.value.length);
  target.type = 'number';
}

回答by Mike Miroshnikov

The evt.target.select()selects content of input type="number"in Chrome, the "if" structure does the same on touch devices.

Chrome 中的evt.target.select()选择内容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);

Unfortunately that "if" prevents that autoselect in Mac Safari, I don't know how to get the same result both in desktop browsers and mobile.

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

回答by nub340

I kind of got this working in angular 1.5 using a nifty custom directive (see example below in typescript).

我使用一个漂亮的自定义指令在 angular 1.5 中完成了这个工作(参见下面的打字稿示例)。

Since it appears there is no way to programmatically select the entire value while the input type="number", the strategy here is to temporarily change the input type from number to text while editing the value, then change it back to the original type on blur.

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

This results in behavior that differs slightly from the native behavior in that it will actually allow you to type in "invalid" data into the field. However, on blur, all of the browser's native number validation logic will kick in and prevent any invalid data from being submitted. I'm sure there's some other gotchas but it's works well enough in Chrome and FireFox for us so I thought I'd share.

这会导致行为与本机行为略有不同,因为它实际上允许您在字段中输入“无效”数据。但是,在模糊时,所有浏览器的本机号码验证逻辑都将启动并防止提交任何无效数据。我确定还有其他一些问题,但它在 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;
    }
} 

回答by Jordan Running

Just like the error message says, you can't use setSelectionRangewith a number input. If you want to modify the selection using JavaScript, you'll have to use <input type="text"/>instead.

正如错误消息所说,您不能使用setSelectionRange数字输入。如果要使用 JavaScript 修改选择,则必须<input type="text"/>改用。