我有以下代码在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"
当前回答
如果有人想在页面加载w/ jQuery(甜蜜的搜索字段)这是我的解决方案
jQuery.fn.focusAndSelect = function() {
return this.each(function() {
$(this).focus();
if (this.setSelectionRange) {
var len = $(this).val().length * 2;
this.setSelectionRange(0, len);
} else {
$(this).val($(this).val());
}
this.scrollTop = 999999;
});
};
(function ($) {
$('#input').focusAndSelect();
})(jQuery);
基于这篇文章。感谢CSS-Tricks.com
其他回答
实际上,可以使用onclick="this.select();",但记住不要将其与disabled="disabled"结合使用——这样就不能工作了,你仍然需要手动选择或多点点击来选择。如果希望锁定要选择的内容值,请结合属性readonly。
Html(你必须把onclick属性放在你想要它在页面上工作的每个输入上)
<input type="text" value="click the input to select" onclick="this.select();"/>
或者一个更好的选择
jQuery(这将适用于页面上的每个文本输入,不需要改变你的html):
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click','input[type=text]',function(){ this.select(); });
});
</script>
输入自动聚焦,onfocus事件:
<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>
这样就可以打开选中所需元素的表单。它的工作原理是使用自动聚焦来命中输入,然后发送自己一个onfocus事件,该事件反过来选择文本。
你可以为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" />
如果你正在寻找一个纯粹的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);"/>