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

其他回答

如果有人想在页面加载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

如果你正在寻找一个纯粹的javascript方法,你也可以使用:

document.createRange().selectNodeContents( element );

这将选择所有的文本,所有主流浏览器都支持。

要触发焦点上的选择,你只需要像这样添加事件监听器:

document.querySelector( element ).addEventListener( 'focusin', function () {

    document.createRange().selectNodeContents( this );

} );

如果你想把它内联到你的HTML中,你可以这样做:

<input type="text" name="myElement" onFocus="document.createRange().selectNodeContents(this)'" value="Some text to select" />

这只是另一种选择。似乎有几种方法可以做到这一点。(这里也提到了document.execCommand("selectall"))

document.querySelector(“# myElement1”)。addEventListener('focusin', function() { .selectNodeContents document.createRange () (); }); </p> .</p> .</p> .</p>单击字段内将不会触发选择,但单击标签进入字段将触发选择 <label for="">JS文件示例<label><br> <input id="myElement1" value="This is some text" /><br> . < br > <label for="">内联示例</label><br> <input id="myElement2" value="This also is some text" onfocus="document.createRange()。selectNodeContents(this);"/>

实际上,可以使用onclick="this.select();",但记住不要将其与disabled="disabled"结合使用——这样就不能工作了,你仍然需要手动选择或多点点击来选择。如果希望锁定要选择的内容值,请结合属性readonly。

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); });
};

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

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

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


更新2021:execCommand现在已弃用。

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

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

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