我有以下代码在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"
当前回答
如果你正在使用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 -所以如果使用其他内容,可以跳过第一行和最后一行。
其他回答
注意:当你考虑onclick="this.select()"时,在第一次点击时,所有字符都会被选中,之后可能你想在输入中编辑一些东西,然后再次点击字符,但它会再次选中所有字符。要解决这个问题,你应该使用onfocus而不是onclick。
用这个:
var textInput = document.querySelector(“input”); textInput.onclick = function() { 文本输入选择开始 = 0; textInput.selectionEnd = textInput.value.length; } <输入类型=“文本”>
If you are just trying to have placeholder text that gets replaced when a user selects the element then it is obviously best practice to use placeholder attribute nowadays. However, if you want to select all of the current value when a field gains focus then a combination of @Cory House and @Toastrackenigma answers seems to be most canonical. Use focus and focusout events, with handlers that set/release the current focus element, and select all when focused. An angular2/typescript example is as follows (but would be trivial to convert to vanilla js):
模板:
<input type="text" (focus)="focus()" (focusout)="focusout()" ... >
组件:
private focused = false;
public focusout = (): void => {
this.focused = false;
};
public focus = (): void => {
if(this.focused) return;
this.focused = true;
// Timeout for cross browser compatibility (Chrome)
setTimeout(() => { document.execCommand('selectall', null, false); });
};
如果你正在使用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 -所以如果使用其他内容,可以跳过第一行和最后一行。
Html(你必须把onclick属性放在你想要它在页面上工作的每个输入上)
<input type="text" value="click the input to select" onclick="this.select();"/>
或者一个更好的选择
jQuery(这将适用于页面上的每个文本输入,不需要改变你的html):
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click','input[type=text]',function(){ this.select(); });
});
</script>