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

旧街凉风 提交于 2019-12-12 09:26:52

问题


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


回答1:


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;



回答2:


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)




回答3:


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


来源:https://stackoverflow.com/questions/5140637/javascript-how-to-get-line-col-caret-position-in-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!