我有以下代码在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"
当前回答
Try:
onclick="this.select()"
这对我来说很有效。
其他回答
我认为通过事件来控制更好。这个变体看起来很直观,也适用于ts:
onFocus={e => {
e.target.select();
}
如果你每次点击都需要selectAll,你可以使用这个:
onClick={e => {
e.target.focus();
e.target.select();
}
Try:
onclick="this.select()"
这对我来说很有效。
你可以替换
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
占位符用来替换值,就像你希望人们能够在文本框中键入而无需多次单击或使用ctrl + a。占位符使它不是一个值,但顾名思义,它是一个占位符。这就是在许多在线表单中使用的“用户名在这里”或“电子邮件”,当你点击它时,“电子邮件”消失,你可以立即开始输入。
你可以使用文档。execCommand(所有主要浏览器都支持)
document.execCommand("selectall", null, false);
选择当前聚焦元素中的所有文本。
更新2021:execCommand现在已弃用。
说实话,这可能是最好的选择,因为它是一个老的IE API,已经被其他浏览器采用了,使用它总是有点奇怪。尽管如此,有一个解决方案可以同时处理<input>字段和可满足元素就很好了。
.select()可能是目前<input>字段的最佳方式。
对于contenteditable,现代的解决方案是使用range API。
我正在寻找一个css唯一的解决方案,发现这适用于iOS浏览器(测试safari和chrome)。
它在桌面chrome上没有相同的行为,但选择的痛苦没有那么大,因为作为用户,你有更多的选项(双击,ctrl-a等):
.select-all-on-touch {
-webkit-user-select: all;
user-select: all;
}