我有以下代码在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"
当前回答
在我看来,列出的答案是不完整的。我在下面链接了两个如何在Angular和JQuery中做到这一点的例子。
该方案具有以下特点:
适用于所有支持JQuery, Safari, Chrome, IE, Firefox等浏览器。 适用于Phonegap/Cordova: Android和IOs。 只选择所有一次输入得到焦点,直到下一个模糊,然后焦点 可以使用多个输入,而且不会出现故障。 Angular指令有很好的重用性,只需添加指令select-all-on-click即可 JQuery可以很容易地修改
JQuery: http://plnkr.co/edit/VZ0o2FJQHTmOMfSPRqpH?p=preview
$("input").blur(function() {
if ($(this).attr("data-selected-all")) {
//Remove atribute to allow select all again on focus
$(this).removeAttr("data-selected-all");
}
});
$("input").click(function() {
if (!$(this).attr("data-selected-all")) {
try {
$(this).selectionStart = 0;
$(this).selectionEnd = $(this).value.length + 1;
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
} catch (err) {
$(this).select();
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
}
}
});
角: http://plnkr.co/edit/llcyAf?p=preview
var app = angular.module('app', []);
//add select-all-on-click to any input to use directive
app.directive('selectAllOnClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var hasSelectedAll = false;
element.on('click', function($event) {
if (!hasSelectedAll) {
try {
//iOS, Safari, thows exception on Chrome etc
this.selectionStart = 0;
this.selectionEnd = this.value.length + 1;
hasSelectedAll = true;
} catch (err) {
//Non iOS option if not supported, e.g. Chrome
this.select();
hasSelectedAll = true;
}
}
});
//On blur reset hasSelectedAll to allow full select
element.on('blur', function($event) {
hasSelectedAll = false;
});
}
};
}]);
其他回答
您不应该再使用这种方法为输入值提供示例。
最好的选择是现在使用占位符HTML属性,如果可能的话:
<label for="userid">User ID</label>
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
这将导致文本显示,除非输入值,消除了选择文本或清除输入的需要。
请注意占位符不能代替标签,因为一旦输入文本,占位符就会消失,并对可访问性造成问题。
在输入字段中使用“占位符”而不是“值”。
捕获单击事件的问题是,文本中的每次后续单击都将再次选择它,而用户可能希望重新定位光标。
对我有用的是声明一个变量selectSearchTextOnClick,并在默认情况下将其设置为true。点击处理程序检查变量是否仍然为true:如果为true,则将其设置为false并执行select()。然后我有一个模糊事件处理程序,将其设置为true。
到目前为止,结果似乎是我所期望的。
(编辑:我忘了说我曾尝试按照某人的建议捕获焦点事件,但这不起作用:焦点事件触发后,点击事件可以触发,立即取消选择文本)。
当.select()在移动平台上不起作用时,这个问题有选项:在iOS设备(移动Safari)上以编程方式选择输入字段中的文本
你所问问题的确切解决方案是:
<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" />