我有以下代码在HTML网页中显示一个文本框。

<input type="text" id="userid" name="userid" value="Please enter the user ID" />

当页面显示时,文本包含“请输入用户ID”消息。但是,我发现用户需要单击3次才能选择所有文本(在本例中是Please enter the user ID)。

是否可以只点击一下就选择整个文本?

编辑:

抱歉,我忘了说:我必须使用input type="text"


当前回答

我认为通过事件来控制更好。这个变体看起来很直观,也适用于ts:

    onFocus={e => {
      e.target.select();
    }

如果你每次点击都需要selectAll,你可以使用这个:

    onClick={e => {
      e.target.focus();
      e.target.select();
    }

其他回答

现场演示

<input id="my_input" style="width: 400px; height: 30px;" value="some text to select">
<br>
<button id="select-bn" style="width: 100px; height: 30px; margin-top: 20px;cursor:pointer;">Select all</button>
<br><br>
OR 
<br><br>
Click to copy
<br><br>
<input id="my_input_copy" style="width: 400px; height: 30px;" value="some text to select and copy">
<br>
<button id="select-bn-copy" style="width: 170px; height: 30px; margin-top: 20px;cursor:pointer;">Click copy text</button>


<script type="text/javascript">
$(document).on('click', '#select-bn', function() {
  $("#my_input").select();
});


//click to select and copy to clipboard

var text_copy_bn = document.getElementById("select-bn-copy");
text_copy_bn.addEventListener('click', function(event) {
  var copy_text = document.getElementById("my_input_copy");
  copy_text.focus();
  copy_text.select();
  try {
    var works = document.execCommand('copy');
    var msg = works ? 'Text copied!' : 'Could not copy!';
    alert(msg);
  } catch (err) {
    alert('Sorry, could not copy');
  }
});
</script>

你可以为HTMLElement使用JavaScript的.select()方法:

<label for="userid">用户ID <input onClick="this.select();" value="Please enter the user ID" ID ="userid" /> .

但显然它在移动版Safari上不起作用。在这些情况下,你可以使用:

<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" id="userid" />

之前发布的解决方案有两个怪癖:

在Chrome中,通过.select()选择不粘-添加一个轻微的超时解决了这个问题。 不可能在聚焦后将光标放置在所需的点上。

这里有一个完整的解决方案,选择焦点上的所有文本,但允许在焦点后选择特定的游标点。

$(function () {
    var focusedElement;
    $(document).on('focus', 'input', function () {
        if (focusedElement == this) return; //already focused, return so user can now place cursor at specific point in input.
        focusedElement = this;
        setTimeout(function () { focusedElement.select(); }, 100); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
    });
});

实际上,可以使用onclick="this.select();",但记住不要将其与disabled="disabled"结合使用——这样就不能工作了,你仍然需要手动选择或多点点击来选择。如果希望锁定要选择的内容值,请结合属性readonly。

在输入字段中使用“占位符”而不是“值”。