我有以下代码在HTML网页中显示一个文本框。

<input type="text" id="userid" name="userid" value="Please enter the user ID" />

当页面显示时,文本包含“请输入用户ID”消息。但是,我发现用户需要单击3次才能选择所有文本(在本例中是Please enter the user ID)。

是否可以只点击一下就选择整个文本?

编辑:

抱歉,我忘了说:我必须使用input type="text"


当前回答

你所问问题的确切解决方案是:

<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" />

其他回答

如果你正在使用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 -所以如果使用其他内容,可以跳过第一行和最后一行。

你可以为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" />

这是一个正常的文本框活动。

单击“1 -设置焦点”

点击2/3(双击)-选择文本

您可以在页面第一次加载时将焦点设置在文本框上,以减少“选择”为单个双击事件。

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>

您不应该再使用这种方法为输入值提供示例。

最好的选择是现在使用占位符HTML属性,如果可能的话:

<label for="userid">User ID</label>
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />

这将导致文本显示,除非输入值,消除了选择文本或清除输入的需要。

请注意占位符不能代替标签,因为一旦输入文本,占位符就会消失,并对可访问性造成问题。