什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?


当前回答

这个会有用的,试试这个

<input id="textField1" onfocus="this.select()" onmouseup="return false" /> 

可以在Safari/IE 9和Chrome上运行,但我没有机会在Firefox上测试。

其他回答

这也适用于iOS:

<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select

注意:如果你在ASP中编程。NET中,您可以使用ScriptManager运行脚本。c#中的RegisterStartupScript:

ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );

或者在其他答案中建议的HTML页面中输入脚本。

通过加入一些函数调用,我可以稍微改进Zach的回答。这个答案的问题是它完全禁用了onMouseUp,从而阻止你在文本框中点击,一旦它有焦点。

这是我的代码:

<input type="text" onfocus="this.select()" onMouseUp="javascript:TextBoxMouseUp();" onMouseDown="javascript:TextBoxMouseDown();" />

<script type="text/javascript">
    var doMouseUp = true;
    function TextBoxMouseDown() {
        doMouseUp = this == document.activeElement;
        return doMouseUp;
    }
    function TextBoxMouseUp() {
        if (doMouseUp)
        { return true; }
        else {
            doMouseUp = true;
            return false;
        }
    }
</script>

这比扎克的回答略有进步。它在IE中工作得很完美,在Chrome中完全不能工作,在FireFox中则是交替成功(几乎每隔一次)。如果有人有一个想法,如何使它可靠地工作在FF或Chrome,请分享。

总之,我想我应该分享我所能做的让这一切更美好。

这不仅仅是Chrome/Safari的问题,我在Firefox 18.0.1中也遇到了类似的问题。有趣的是,这不会发生在MSIE!这里的问题是第一个鼠标点击事件强制取消选择输入内容,所以忽略第一个事件。

$(':text').focus(function(){
    $(this).one('mouseup', function(event){
        event.preventDefault();
    }).select();
});

timeOut方法会导致一种奇怪的行为,并且阻塞每个鼠标升起事件,您无法删除再次单击输入元素的选择。

HTML:

var textFiled = document.getElementById("text-filed"); 文本文件。addEventListener("focus", function() {this.select();}); 输入你的文本:<input type=" Text " id=" Text -filed" value="test with filed Text ">

使用JQuery:

$("#text-filed").focus(function() { $(this).select(); } );

使用React JS:

在各自的组成部分-

<input
  type="text"
  value="test"
  onFocus={e => e.target.select()}
/>