我有以下代码在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"
当前回答
这是一个正常的文本框活动。
单击“1 -设置焦点”
点击2/3(双击)-选择文本
您可以在页面第一次加载时将焦点设置在文本框上,以减少“选择”为单个双击事件。
其他回答
如果有人想在页面加载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
使用占位符="请输入用户ID"而不是value="请输入用户ID"是这种情况下的最佳方法,但该函数在某些情况下可能有用。
<input>元素已经可以监听焦点事件。我们可以将事件监听器添加到它而不是文档中,并且不需要再监听单击。
纯JavaScript:
document.getElementById("userid").addEventListener("focus", function() {
this.select();
});
JQuery:
$("#userid").on("focus", function() {
this.select();
});
你可以用这个。setSelectionRange(0, this.value.length)而不是this.select()取决于你的目的,但这将不适用于某些输入类型,如number。
我在vue应用程序中使用焦点属性
<input @focus="$event.target.select()" />
你所问问题的确切解决方案是:
<input type="text" id="userid" name="userid" value="Please enter the user ID" onClick="this.setSelectionRange(0, this.value.length)"/>
但是我猜想,您试图在输入中显示“请输入用户ID”作为占位符或提示。 因此,您可以使用以下更有效的解决方案:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
当.select()在移动平台上不起作用时,这个问题有选项:在iOS设备(移动Safari)上以编程方式选择输入字段中的文本