我有以下代码在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()"
这对我来说很有效。
其他回答
当.select()在移动平台上不起作用时,这个问题有选项:在iOS设备(移动Safari)上以编程方式选择输入字段中的文本
用这个:
var textInput = document.querySelector(“input”); textInput.onclick = function() { 文本输入选择开始 = 0; textInput.selectionEnd = textInput.value.length; } <输入类型=“文本”>
下面是React中的一个例子,但如果你喜欢,它可以在香草JS上翻译成jQuery:
class Num extends React.Component {
click = ev => {
const el = ev.currentTarget;
if(document.activeElement !== el) {
setTimeout(() => {
el.select();
}, 0);
}
}
render() {
return <input type="number" min={0} step={15} onMouseDown={this.click} {...this.props} />
}
}
这里的技巧是使用onMouseDown,因为元素在“click”事件触发时已经收到了焦点(因此activeElement检查将失败)。
activeElement检查是必要的,这样用户就可以将光标定位到他们想要的位置,而不必不断地重新选择整个输入。
超时是必要的,因为否则文本将被选中,然后立即取消选中,因为我猜浏览器在后面会进行光标定位检查。
最后,el = ev。currentTarget在React中是必要的,因为React重用事件对象,当setTimeout触发时,你将失去合成事件。
你可以使用文档。execCommand(所有主要浏览器都支持)
document.execCommand("selectall", null, false);
选择当前聚焦元素中的所有文本。
更新2021:execCommand现在已弃用。
说实话,这可能是最好的选择,因为它是一个老的IE API,已经被其他浏览器采用了,使用它总是有点奇怪。尽管如此,有一个解决方案可以同时处理<input>字段和可满足元素就很好了。
.select()可能是目前<input>字段的最佳方式。
对于contenteditable,现代的解决方案是使用range API。
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); });
};