我有以下代码在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"
当前回答
注意:当你考虑onclick="this.select()"时,在第一次点击时,所有字符都会被选中,之后可能你想在输入中编辑一些东西,然后再次点击字符,但它会再次选中所有字符。要解决这个问题,你应该使用onfocus而不是onclick。
其他回答
我正在寻找一个css唯一的解决方案,发现这适用于iOS浏览器(测试safari和chrome)。
它在桌面chrome上没有相同的行为,但选择的痛苦没有那么大,因为作为用户,你有更多的选项(双击,ctrl-a等):
.select-all-on-touch {
-webkit-user-select: all;
user-select: all;
}
你可以为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" />
您不应该再使用这种方法为输入值提供示例。
最好的选择是现在使用占位符HTML属性,如果可能的话:
<label for="userid">User ID</label>
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
这将导致文本显示,除非输入值,消除了选择文本或清除输入的需要。
请注意占位符不能代替标签,因为一旦输入文本,占位符就会消失,并对可访问性造成问题。
如果你正在使用AngularJS,你可以使用一个自定义指令来方便访问:
define(['angular'], function () {
angular.module("selectionHelper", [])
.directive('selectOnClick', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function () {
this.select();
});
}
};
});
});
现在你可以这样使用它:
<input type="text" select-on-click ... />
这个示例带有requirejs -所以如果使用其他内容,可以跳过第一行和最后一行。
Try:
onclick="this.select()"
这对我来说很有效。