我有以下代码在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"
当前回答
之前发布的解决方案有两个怪癖:
在Chrome中,通过.select()选择不粘-添加一个轻微的超时解决了这个问题。 不可能在聚焦后将光标放置在所需的点上。
这里有一个完整的解决方案,选择焦点上的所有文本,但允许在焦点后选择特定的游标点。
$(function () {
var focusedElement;
$(document).on('focus', 'input', function () {
if (focusedElement == this) return; //already focused, return so user can now place cursor at specific point in input.
focusedElement = this;
setTimeout(function () { focusedElement.select(); }, 100); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
});
});
其他回答
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>
如果有人想在页面加载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
你可以为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" />
我在vue应用程序中使用焦点属性
<input @focus="$event.target.select()" />
注意:当你考虑onclick="this.select()"时,在第一次点击时,所有字符都会被选中,之后可能你想在输入中编辑一些东西,然后再次点击字符,但它会再次选中所有字符。要解决这个问题,你应该使用onfocus而不是onclick。