我有以下代码在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.
});
});
捕获单击事件的问题是,文本中的每次后续单击都将再次选择它,而用户可能希望重新定位光标。
对我有用的是声明一个变量selectSearchTextOnClick,并在默认情况下将其设置为true。点击处理程序检查变量是否仍然为true:如果为true,则将其设置为false并执行select()。然后我有一个模糊事件处理程序,将其设置为true。
到目前为止,结果似乎是我所期望的。
(编辑:我忘了说我曾尝试按照某人的建议捕获焦点事件,但这不起作用:焦点事件触发后,点击事件可以触发,立即取消选择文本)。
如果有人想在页面加载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
以下是Shoban回答的可重复使用版本:
<input type="text" id="userid" name="userid"
value="Please enter the user ID" onfocus="Clear(this);"
/>
function Clear(elem)
{
elem.value='';
}
这样就可以为多个元素重用clear脚本。
这是一个正常的文本框活动。
单击“1 -设置焦点”
点击2/3(双击)-选择文本
您可以在页面第一次加载时将焦点设置在文本框上,以减少“选择”为单个双击事件。