我有以下代码在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"
当前回答
输入自动聚焦,onfocus事件:
<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>
这样就可以打开选中所需元素的表单。它的工作原理是使用自动聚焦来命中输入,然后发送自己一个onfocus事件,该事件反过来选择文本。
其他回答
我在vue应用程序中使用焦点属性
<input @focus="$event.target.select()" />
注意:当你考虑onclick="this.select()"时,在第一次点击时,所有字符都会被选中,之后可能你想在输入中编辑一些东西,然后再次点击字符,但它会再次选中所有字符。要解决这个问题,你应该使用onfocus而不是onclick。
像这样的Html <input type="text" value="点击输入选择" onclick="javascript:textSelector(this)" / >
和javascript代码没有绑定
function textSelector(ele){
$(ele).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。占位符使它不是一个值,但顾名思义,它是一个占位符。这就是在许多在线表单中使用的“用户名在这里”或“电子邮件”,当你点击它时,“电子邮件”消失,你可以立即开始输入。
如果你正在寻找一个纯粹的javascript方法,你也可以使用:
document.createRange().selectNodeContents( element );
这将选择所有的文本,所有主流浏览器都支持。
要触发焦点上的选择,你只需要像这样添加事件监听器:
document.querySelector( element ).addEventListener( 'focusin', function () {
document.createRange().selectNodeContents( this );
} );
如果你想把它内联到你的HTML中,你可以这样做:
<input type="text" name="myElement" onFocus="document.createRange().selectNodeContents(this)'" value="Some text to select" />
这只是另一种选择。似乎有几种方法可以做到这一点。(这里也提到了document.execCommand("selectall"))
document.querySelector(“# myElement1”)。addEventListener('focusin', function() { .selectNodeContents document.createRange () (); }); </p> .</p> .</p> .</p>单击字段内将不会触发选择,但单击标签进入字段将触发选择 <label for="">JS文件示例<label><br> <input id="myElement1" value="This is some text" /><br> . < br > <label for="">内联示例</label><br> <input id="myElement2" value="This also is some text" onfocus="document.createRange()。selectNodeContents(this);"/>