【问题标题】:How to get the caret column (not pixels) position in a textarea, in characters, from the start?如何从一开始就以字符形式获取文本区域中的插入符号列(不是像素)位置?
【发布时间】:2010-09-20 19:04:57
【问题描述】:

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

例如:This is| a text

这应该返回7

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

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

如果单词“is”被突出显示,那么它将返回'This ', 'is', ' a text'

【问题讨论】:

标签: javascript textarea caret


【解决方案1】:

使用 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 插件,它允许您执行此操作以及更多...

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

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

【讨论】:

  • 当插入符号放置在空行上时,这不会区分插入符号的位置。见stackoverflow.com/questions/3053542/…
  • 这个答案不处理空行问题。
  • 如何将它用于 CONTENTEDITABLE div?
  • 您可能想稍微改写一下这个答案,Safari (and other Gecko based browsers) 似乎暗示 Safari 使用 Gecko。 Gecko 是 Mozilla 的引擎; Safari 使用 WebKit。
  • 位置 0 的插入符号将无法通过测试 if (el.selectionStart) { return el.selectionStart; }...
【解决方案2】:

2010 年 9 月 5 日更新

看到每个人似乎都被引导到这里来解决这个问题,我将我的答案添加到一个类似的问题中,其中包含与此答案相同的代码,但对于感兴趣的人来说具有完整的背景:

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

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

请注意,文本区域必须具有焦点,此功能才能在 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
    };
}

【讨论】:

  • 对不起,'range && range.parentElement()' 是什么意思?
  • 如果我们想在 IE 中获取插入符号的位置(如果选择为空),则会出现问题。在这种情况下,它返回 0 作为开始,string length 作为结束(如果我们使用 true 而不是 range && range.parentElement( ) == el).
  • @sergzach:range && range.parentElement() == el 用于测试选择是否在文本区域内并且是必要的。 只要文本区域有焦点,获取插入符号位置的函数就没有问题。如果不确定,请在调用getInputSelection() 之前调用textarea 的focus() 方法。我会在答案中添加注释。
  • @Tim:当点击 div 元素以显示选择时,“开始”和“结束”总是相同的。
  • @Misha:这不是函数的错:这是函数执行时实际选择的内容。关闭警报框后,您可以直观地看到它。正如我在对您最近的问题的回答中提到的,两种可能的解决方法是使用 mousedown 事件或将 unselectable="on" 添加到 <div> 元素。
【解决方案3】:

我修改了上面的函数来解释 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; 
}

【讨论】:

    【解决方案4】:

    如果不支持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

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 1970-01-01
      • 2012-11-01
      • 2011-05-26
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多