首页 文章

如何从一开始就以字符形式在textarea中获取插入符号列(不是像素)的位置?

提问于
浏览
174

你如何使用JavaScript获得插入 <textarea> 的插入位置?

例如: This is| a text

这应该返回 7 .

如何让它返回光标/选择周围的字符串?

例如: 'This is', '', ' a text' .

如果单词“is”突出显示,则返回 'This ', 'is', ' a text' .

4 回答

  • 57

    如果您不必支持IE,则可以使用 textareaselectionStartselectionEnd 属性 .

    要获得插入位置,只需使用 selectionStart

    function getCaretPosition(textarea) {
      return textarea.selectionStart
    }
    

    要获取选择周围的字符串,请使用以下代码:

    function getSurroundingSelection(textarea) {
      return [textarea.value.substring(0, textarea.selectionStart)
             ,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
             ,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
    }
    

    Demo on JSFiddle .

    另见HTMLTextAreaElement docs .

  • 3

    使用Firefox,Safari(以及其他基于Gecko的浏览器),您可以轻松使用textarea.selectionStart,但对于不起作用的IE,您必须执行以下操作:

    function getCaret(node) {
      if (node.selectionStart) {
        return node.selectionStart;
      } else if (!document.selection) {
        return 0;
      }
    
      var c = "\001",
          sel = document.selection.createRange(),
          dul = sel.duplicate(),
          len = 0;
    
      dul.moveToElementText(node);
      sel.text = c;
      len = dul.text.indexOf(c);
      sel.moveStart('character',-1);
      sel.text = "";
      return len;
    }
    

    complete code here

    我还建议你查看jQuery FieldSelection插件,它可以让你做到这一点以及更多......

    Edit: 我实际上重新实现了上面的代码:

    function getCaret(el) { 
      if (el.selectionStart) { 
        return el.selectionStart; 
      } else if (document.selection) { 
        el.focus(); 
    
        var r = document.selection.createRange(); 
        if (r == null) { 
          return 0; 
        } 
    
        var re = el.createTextRange(), 
            rc = re.duplicate(); 
        re.moveToBookmark(r.getBookmark()); 
        rc.setEndPoint('EndToStart', re); 
    
        return rc.text.length; 
      }  
      return 0; 
    }
    

    检查示例here .

  • 171

    Updated 5 September 2010

    看到每个人似乎都在这里针对这个问题,我将我的答案添加到一个类似的问题,其中包含与此答案相同的代码,但对于那些感兴趣的人有完整的背景:

    IE's document.selection.createRange doesn't include leading or trailing blank lines

    在IE中考虑尾随换行是很棘手的,我没有看到任何正确执行此操作的解决方案,包括此问题的任何其他答案 . 但是,可以使用以下函数,它将在 <textarea> 或文本 <input> 中返回选择的开始和结束(在插入符号的情况下相同) .

    请注意,textarea必须具有焦点才能使此功能在IE中正常工作 . 如有疑问,请先调用textarea的 focus() 方法 .

    function getInputSelection(el) {
        var start = 0, end = 0, normalizedValue, range,
            textInputRange, len, endRange;
    
        if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
            start = el.selectionStart;
            end = el.selectionEnd;
        } else {
            range = document.selection.createRange();
    
            if (range && range.parentElement() == el) {
                len = el.value.length;
                normalizedValue = el.value.replace(/\r\n/g, "\n");
    
                // Create a working TextRange that lives only in the input
                textInputRange = el.createTextRange();
                textInputRange.moveToBookmark(range.getBookmark());
    
                // Check if the start and end of the selection are at the very end
                // of the input, since moveStart/moveEnd doesn't return what we want
                // in those cases
                endRange = el.createTextRange();
                endRange.collapse(false);
    
                if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                    start = end = len;
                } else {
                    start = -textInputRange.moveStart("character", -len);
                    start += normalizedValue.slice(0, start).split("\n").length - 1;
    
                    if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                        end = len;
                    } else {
                        end = -textInputRange.moveEnd("character", -len);
                        end += normalizedValue.slice(0, end).split("\n").length - 1;
                    }
                }
            }
        }
    
        return {
            start: start,
            end: end
        };
    }
    
  • 1

    我修改了上面的函数来解释IE中的回车问题 . 它没有经过测试,但我在代码中做了类似的事情,所以它应该是可行的 .

    function getCaret(el) {
      if (el.selectionStart) { 
        return el.selectionStart; 
      } else if (document.selection) { 
        el.focus(); 
    
        var r = document.selection.createRange(); 
        if (r == null) { 
          return 0; 
        } 
    
        var re = el.createTextRange(), 
        rc = re.duplicate(); 
        re.moveToBookmark(r.getBookmark()); 
        rc.setEndPoint('EndToStart', re); 
    
        var add_newlines = 0;
        for (var i=0; i<rc.text.length; i++) {
          if (rc.text.substr(i, 2) == '\r\n') {
            add_newlines += 2;
            i++;
          }
        }
    
        //return rc.text.length + add_newlines;
    
        //We need to substract the no. of lines
        return rc.text.length - add_newlines; 
      }  
      return 0; 
    }
    

相关问题