Javascript:如何在textarea获得line / col插入位置?

时间:2011-02-28 10:12:50

标签: javascript textarea caret

我找不到解决方案。我试图假设\ n符号的数量与行数相同,但有时这种方法工作不正确(例如从剪贴板粘贴文本后) 我尝试过不同的jQuery插件,但仍然没有成功。 任何想法?

3 个答案:

答案 0 :(得分:2)

为什么不这样做:

仅将文字内容提取至selectionStart,然后在eol

分割,使其成为数组
p = $('#Form_config').val().substr(0, $('#Form_config')[0].selectionStart).split("\n");

// line is the number of lines
line = p.length;

// col is the length of the last line
col = p[p.length-1].length;

答案 1 :(得分:1)

决策并非如此简单,并且需要大量的javascript代码。所以,最后我使用了Marijn Haverbeke的CodeMirror Project(https://github.com/marijnh/CodeMirror)

答案 2 :(得分:0)

尝试使用它:

var pos = getCaretPos(document.formName.textareaName);

function getCaretPos(obj)
{
  obj.focus();

  if(obj.selectionStart) return obj.selectionStart;//Gecko
  else if (document.selection)//IE
  {
    var sel = document.selection.createRange();
    var clone = sel.duplicate();
    sel.collapse(true);
    clone.moveToElementText(obj);
    clone.setEndPoint('EndToEnd', sel);
    return clone.text.length;
  }

  return 0;
}
相关问题