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

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

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

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

编辑:

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


当前回答

捕获单击事件的问题是,文本中的每次后续单击都将再次选择它,而用户可能希望重新定位光标。

对我有用的是声明一个变量selectSearchTextOnClick,并在默认情况下将其设置为true。点击处理程序检查变量是否仍然为true:如果为true,则将其设置为false并执行select()。然后我有一个模糊事件处理程序,将其设置为true。

到目前为止,结果似乎是我所期望的。

(编辑:我忘了说我曾尝试按照某人的建议捕获焦点事件,但这不起作用:焦点事件触发后,点击事件可以触发,立即取消选择文本)。

其他回答

你可以使用文档。execCommand(所有主要浏览器都支持)

document.execCommand("selectall", null, false);

选择当前聚焦元素中的所有文本。


更新2021:execCommand现在已弃用。

说实话,这可能是最好的选择,因为它是一个老的IE API,已经被其他浏览器采用了,使用它总是有点奇怪。尽管如此,有一个解决方案可以同时处理<input>字段和可满足元素就很好了。

.select()可能是目前<input>字段的最佳方式。

对于contenteditable,现代的解决方案是使用range API。

如果有人想在页面加载w/ jQuery(甜蜜的搜索字段)这是我的解决方案

jQuery.fn.focusAndSelect = function() {
    return this.each(function() {
        $(this).focus();
        if (this.setSelectionRange) {
            var len = $(this).val().length * 2;
            this.setSelectionRange(0, len);
        } else {
            $(this).val($(this).val());
        }
        this.scrollTop = 999999;
    });
};

(function ($) {
    $('#input').focusAndSelect();
})(jQuery);

基于这篇文章。感谢CSS-Tricks.com

我在vue应用程序中使用焦点属性

<input @focus="$event.target.select()" />

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>

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

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