开发者

Javascript: how to get line/col caret position in textarea?

开发者 https://www.devze.com 2023-02-14 08:20 出处:网络
I can not find the solution. I\'ve tried to assume that count of\\n symbols is the same with lines count, but someti开发者_运维技巧mes this method works incorrectly (e.g. after paste text from clipboa

I can not find the solution. I've tried to assume that count of \n symbols is the same with lines count, but someti开发者_运维技巧mes this method works incorrectly (e.g. after paste text from clipboard) i've tried different jQuery plugins, but still unsuccessfully. any idea?


Why not just do this:

Take the text content only up to selectionStart then make it an array by splitting at 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;


Try to use this:

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;
}


The descision is not so simple and requieres large amount of javascript code. So, finally i've used CodeMirror Project by Marijn Haverbeke (https://github.com/marijnh/CodeMirror)

0

精彩评论

暂无评论...
验证码 换一张
取 消