【问题标题】:jQuery - get current text selection within input fieldjQuery - 在输入字段中获取当前文本选择
【发布时间】:2017-09-12 13:58:02
【问题描述】:

我有几个具有相同类名的输入框。我希望能够获取当前突出显示的文本并确切知道该文本在哪个输入框中。我当前的方法是这样的:

 $(document).on("mouseup", ".element", function(){
    var text = "";
    var activeEl = document.activeElement;
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
    if (
    (activeElTagName == "textarea") || (activeElTagName == "input" &&
    /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
    (typeof activeEl.selectionStart == "number")
    ) {
        text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
    } else if (window.getSelection) {
        text = window.getSelection().toString();
   }
});

这给了我当前的文本选择,我可以调用$(this) 来访问突出显示文本所在的元素。

但是,我当前方法的问题是,如果您开始单击然后在文本框外拖动,例如在文本框左边缘之外,您将在框中突出显示文本,但事件会不注册,因为鼠标单击在输入字段范围之外结束。我该如何解决这个问题?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以在事件处理程序的范围之外设置像 isMouseDown 这样的变量,如下所示:

    var isMouseDown = false;
    
    $(document).on("mousedown", ".element", function(){
      isMouseDown = true;
    });
    
    $(document).on("mouseup", document, function(){
      if (isMouseDown) {
        var text = "";
        var activeEl = document.activeElement;
        var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
        if (
        (activeElTagName == "textarea") || (activeElTagName == "input" &&
        /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
        (typeof activeEl.selectionStart == "number")
        ) {
            text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
        } else if (window.getSelection()) {
            text = window.getSelection().toString();
        }
      }
      isMouseDown = false;
    });
    

    【讨论】:

      【解决方案2】:

      您可以在输入框上使用 onselect 事件。当您选择文本时,会重新注册一个 onselect 事件。之后可以找到高亮文本的起点和高亮文本的终点。

      见下面的sn-p

      $(".boxes").on('select', function() {
        if (window.getSelection) {
          text = window.getSelection().toString();
          var start_index = this.selectionStart;
          var end_index = this.selectionEnd;
          console.log(this.value.substr(start_index, end_index));
        }
      }) //end mouseover
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <input id="in1" class="boxes">
      <input id="in1" class="boxes">
      <input id="in1" class="boxes">
      <input id="in1" class="boxes">
      <input id="in1" class="boxes">

      【讨论】:

        【解决方案3】:

        您可以将多个事件绑定到一个处理程序。
        所以也绑定mouseleave吧!

        $(document).on("mouseup mouseleave", ".element", function(){
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-12-17
          • 1970-01-01
          • 2013-08-27
          • 1970-01-01
          • 2019-08-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多