Javascript iOS和Android[类型=数量]设置选择范围与选择

Javascript iOS和Android[类型=数量]设置选择范围与选择,javascript,input,selection,Javascript,Input,Selection,我试图通过单击来突出显示输入[type=number]的文本。我最初尝试了select(),它适用于Chrome(Android),但不适用于Safari(iOS) 所以我找到了一段代码,建议我尝试setSelectionRange(0,nativeEl.value.length) 这在iOS上运行得很好!然而,对于Chrome,它崩溃了: Uncaught DOMException: Failed to execute 'setSelectionRange' on 'HTMLInputElem

我试图通过单击来突出显示
输入[type=number]
的文本。我最初尝试了
select()
,它适用于Chrome(Android),但不适用于Safari(iOS)

所以我找到了一段代码,建议我尝试
setSelectionRange(0,nativeEl.value.length)

这在iOS上运行得很好!然而,对于Chrome,它崩溃了:

Uncaught DOMException: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection.
因此,一种方法适用于一种平台,而不是另一种,反之亦然

我的问题是,在没有浏览器嗅探的情况下,确定最佳平台差异的最佳方法是什么
setSelectionRange
出现在
input
的Chrome和Safari实例上。因此,检查该属性是多余的

到目前为止,我提出的最佳代码如下:

let nativeEl: HTMLInputElement = this.el.nativeElement.querySelector('input');

if (nativeEl) {
  if (nativeEl.setSelectionRange) {
    // select the text from start to end
    try {
      nativeEl.setSelectionRange(0, nativeEl.value.length);
    } catch (e) {
      nativeEl.select();
    }
  }

  nativeEl.select();
}

但依赖catch语句似乎是一种反模式。有更好的方法吗?

成功执行nativeEl.setSelectionRange(0,nativeEl.value.length)后会发生什么;?您正在调用nativeEl.select();在if(nativeEl.setSelectionRange){…}之后,使用else{nativeEl.select();}?@D.Braun不是更好吗?不幸的是,Chrome有属性
setSelectionRange
,这会导致Chrome(而不是Safari)崩溃。我的意思是:if(nativeEl){if(nativeEl.setSelectionRange){//从头到尾选择文本,尝试{nativeEl.setSelectionRange(0,nativeEl.value.length);}catch(e){nativeEl.select();}}否则{nativeEl.select();}}我知道这不是答案。这只是一条注释。:-,这可能会有帮助: