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

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

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

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

编辑:

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


当前回答

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

我正在寻找一个css唯一的解决方案,发现这适用于iOS浏览器(测试safari和chrome)。

它在桌面chrome上没有相同的行为,但选择的痛苦没有那么大,因为作为用户,你有更多的选项(双击,ctrl-a等):

.select-all-on-touch {
    -webkit-user-select: all;
    user-select: all;
}

之前发布的解决方案有两个怪癖:

在Chrome中,通过.select()选择不粘-添加一个轻微的超时解决了这个问题。 不可能在聚焦后将光标放置在所需的点上。

这里有一个完整的解决方案,选择焦点上的所有文本,但允许在焦点后选择特定的游标点。

$(function () {
    var focusedElement;
    $(document).on('focus', 'input', function () {
        if (focusedElement == this) return; //already focused, return so user can now place cursor at specific point in input.
        focusedElement = this;
        setTimeout(function () { focusedElement.select(); }, 100); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
    });
});

在我看来,列出的答案是不完整的。我在下面链接了两个如何在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;
      });
    }
  };
}]);

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