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

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

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

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

编辑:

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


当前回答

如果你正在寻找一个纯粹的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);"/>

其他回答

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>

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

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

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

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

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

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