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

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

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

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

编辑:

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


当前回答

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

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

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


更新2021:execCommand现在已弃用。

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

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

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

其他回答

现场演示

<input id="my_input" style="width: 400px; height: 30px;" value="some text to select">
<br>
<button id="select-bn" style="width: 100px; height: 30px; margin-top: 20px;cursor:pointer;">Select all</button>
<br><br>
OR 
<br><br>
Click to copy
<br><br>
<input id="my_input_copy" style="width: 400px; height: 30px;" value="some text to select and copy">
<br>
<button id="select-bn-copy" style="width: 170px; height: 30px; margin-top: 20px;cursor:pointer;">Click copy text</button>


<script type="text/javascript">
$(document).on('click', '#select-bn', function() {
  $("#my_input").select();
});


//click to select and copy to clipboard

var text_copy_bn = document.getElementById("select-bn-copy");
text_copy_bn.addEventListener('click', function(event) {
  var copy_text = document.getElementById("my_input_copy");
  copy_text.focus();
  copy_text.select();
  try {
    var works = document.execCommand('copy');
    var msg = works ? 'Text copied!' : 'Could not copy!';
    alert(msg);
  } catch (err) {
    alert('Sorry, could not copy');
  }
});
</script>

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

单击“1 -设置焦点”

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

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

输入自动聚焦,onfocus事件:

<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>

这样就可以打开选中所需元素的表单。它的工作原理是使用自动聚焦来命中输入,然后发送自己一个onfocus事件,该事件反过来选择文本。

下面是React中的一个例子,但如果你喜欢,它可以在香草JS上翻译成jQuery:

class Num extends React.Component {

    click = ev => {
        const el = ev.currentTarget;
        if(document.activeElement !== el) {
            setTimeout(() => {
                el.select();    
            }, 0);
        }
    }

    render() {
        return <input type="number" min={0} step={15} onMouseDown={this.click} {...this.props} />
    }
}

这里的技巧是使用onMouseDown,因为元素在“click”事件触发时已经收到了焦点(因此activeElement检查将失败)。

activeElement检查是必要的,这样用户就可以将光标定位到他们想要的位置,而不必不断地重新选择整个输入。

超时是必要的,因为否则文本将被选中,然后立即取消选中,因为我猜浏览器在后面会进行光标定位检查。

最后,el = ev。currentTarget在React中是必要的,因为React重用事件对象,当setTimeout触发时,你将失去合成事件。

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