我有以下代码在HTML网页中显示一个文本框。
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
当页面显示时,文本包含“请输入用户ID”消息。但是,我发现用户需要单击3次才能选择所有文本(在本例中是Please enter the user ID)。
是否可以只点击一下就选择整个文本?
编辑:
抱歉,我忘了说:我必须使用input type="text"
我有以下代码在HTML网页中显示一个文本框。
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
当页面显示时,文本包含“请输入用户ID”消息。但是,我发现用户需要单击3次才能选择所有文本(在本例中是Please enter the user ID)。
是否可以只点击一下就选择整个文本?
编辑:
抱歉,我忘了说:我必须使用input type="text"
当前回答
你可以使用文档。execCommand(所有主要浏览器都支持)
document.execCommand("selectall", null, false);
选择当前聚焦元素中的所有文本。
更新2021:execCommand现在已弃用。
说实话,这可能是最好的选择,因为它是一个老的IE API,已经被其他浏览器采用了,使用它总是有点奇怪。尽管如此,有一个解决方案可以同时处理<input>字段和可满足元素就很好了。
.select()可能是目前<input>字段的最佳方式。
对于contenteditable,现代的解决方案是使用range API。
其他回答
你可以使用文档。execCommand(所有主要浏览器都支持)
document.execCommand("selectall", null, false);
选择当前聚焦元素中的所有文本。
更新2021:execCommand现在已弃用。
说实话,这可能是最好的选择,因为它是一个老的IE API,已经被其他浏览器采用了,使用它总是有点奇怪。尽管如此,有一个解决方案可以同时处理<input>字段和可满足元素就很好了。
.select()可能是目前<input>字段的最佳方式。
对于contenteditable,现代的解决方案是使用range API。
Try:
onclick="this.select()"
这对我来说很有效。
我在vue应用程序中使用焦点属性
<input @focus="$event.target.select()" />
用这个:
var textInput = document.querySelector(“input”); textInput.onclick = function() { 文本输入选择开始 = 0; textInput.selectionEnd = textInput.value.length; } <输入类型=“文本”>
If you are just trying to have placeholder text that gets replaced when a user selects the element then it is obviously best practice to use placeholder attribute nowadays. However, if you want to select all of the current value when a field gains focus then a combination of @Cory House and @Toastrackenigma answers seems to be most canonical. Use focus and focusout events, with handlers that set/release the current focus element, and select all when focused. An angular2/typescript example is as follows (but would be trivial to convert to vanilla js):
模板:
<input type="text" (focus)="focus()" (focusout)="focusout()" ... >
组件:
private focused = false;
public focusout = (): void => {
this.focused = false;
};
public focus = (): void => {
if(this.focused) return;
this.focused = true;
// Timeout for cross browser compatibility (Chrome)
setTimeout(() => { document.execCommand('selectall', null, false); });
};