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


当前回答

如果你把这些事件链接在一起,我相信就不需要使用.one了,就像本文其他地方建议的那样。

例子:

$('input.your_element').focus( function () {
    $(this).select().mouseup( function (e) {
        e.preventDefault();
    });
});

其他回答

如果你把这些事件链接在一起,我相信就不需要使用.one了,就像本文其他地方建议的那样。

例子:

$('input.your_element').focus( function () {
    $(this).select().mouseup( function (e) {
        e.preventDefault();
    });
});

jQuery不是JavaScript,在某些情况下JavaScript更容易使用。

看看这个例子:

<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>

来源:CSS Tricks, MDN

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()}
/>

像@Travis和@Mari一样,我想在用户点击时自动选择,这意味着防止鼠标起动事件的默认行为,但不阻止用户四处点击。我提出的解决方案基于鼠标点击所涉及的事件顺序,适用于IE11、Chrome 45、Opera 32和Firefox 29(这些都是我目前安装的浏览器)。

当你点击一个没有焦点的文本输入时,你会得到这些事件(以及其他):

mousedown:响应你的点击。默认处理在必要时提高焦点并设置选择开始。 focus:作为鼠标按下的默认处理的一部分。 mouseup:完成你的点击,其默认处理将设置选择结束。

单击已具有焦点的文本输入时,将跳过焦点事件。正如@Travis和@Mari都敏锐地注意到的那样,只有当焦点事件发生时,才需要阻止默认的mouseup处理。然而,由于没有“焦点没有发生”事件,我们需要推断这一点,这可以在mousedown处理程序中完成。

@Mari的解决方案需要导入jQuery,这是我想避免的。@Travis的解决方案通过检查document.activeElement来做到这一点。我不知道为什么他的解决方案不能跨浏览器工作,但有另一种方法来跟踪文本输入是否有焦点:简单地跟随它的焦点和模糊事件。

下面是适合我的代码:

  function MakeTextBoxAutoSelect(input)
  {
    var blockMouseUp = false;
    var inputFocused = false;

    input.onfocus =
      function ()
      {
        try
        {
          input.selectionStart = 0;
          input.selectionEnd = input.value.length;
        }
        catch (error)
        {
          input.select();
        }

        inputFocused = true;
      };

    input.onblur =
      function ()
      {
        inputFocused = false;
      };

    input.onmousedown =
      function ()
      {
        blockMouseUp = !inputFocused;
      };

    input.onmouseup =
      function ()
      {
        if (blockMouseUp)
          return false;
      };
  }

我希望这对某人有所帮助。: -)

$(document).ready(function() {
    $("input:text").focus(function() { $(this).select(); } );
});