使用 JavaScript 单击时如何选择 HTML 文本输入中的所有文本

只需单击一下即可选择整个文本非常简单。
我们可以使用以下 JavaScript 代码片段:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <div>
      Input Text:
      <input onClick="this.select();" type="text" value="Sample Text">
    </div>
  </body>
</html>

但是,它不适用于移动 Safari。
在这种情况下,我们可以使用:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
  </head>
  <body>
    <div>
      Input Text:
      <input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" />
    </div>
  </body>
</html>

HTMLInputElement.select() 方法选择包含文本字段的 <textarea> 元素或者 <input> 元素中的整个文本。

但是无法将光标放置在对焦后的所需点上。
这是另一种解决方案,它结合了焦点上的所有文本选择,并允许在焦点后选择特定的光标点:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <div>
      Input Text:
      <input value="Sample Text" />
    </div>
    <script>
      $(function() {
        let focusedElement;
        $(document).on('focus', 'input', function() {
            if(focusedElement == this) return; //已经聚焦,返回以便用户可以将光标放在特定的入口点
            focusedElement = this;
            setTimeout(function() {
              focusedElement.select();
            }, 100); //选择任何焦点字段中的所有文本,以便轻松重新输入。 延迟是为了让焦点“粘”在选择上。
          });
      });
    </script>
  </body>
</html>

HTMLElement.focus() 方法将焦点设置在给定元素上(如果它可以被聚焦)。
默认情况下,焦点元素将接收键盘和类似事件。

日期:2020-06-02 22:16:26 来源:oir作者:oir