我有以下代码在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"
当前回答
在输入字段中使用“占位符”而不是“值”。
其他回答
输入自动聚焦,onfocus事件:
<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>
这样就可以打开选中所需元素的表单。它的工作原理是使用自动聚焦来命中输入,然后发送自己一个onfocus事件,该事件反过来选择文本。
Try:
onclick="this.select()"
这对我来说很有效。
在我看来,列出的答案是不完整的。我在下面链接了两个如何在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 <input type="text" value="点击输入选择" onclick="javascript:textSelector(this)" / >
和javascript代码没有绑定
function textSelector(ele){
$(ele).select();
}
我在vue应用程序中使用焦点属性
<input @focus="$event.target.select()" />