繁体   English   中英

Javascript:如何获取textarea中的line / col插入符号位置?

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

我找不到解决方案。 我试图假定\\ n符号的数量与行数相同,但是有时此方法无法正常工作(例如,从剪贴板粘贴文本后),但是我尝试了不同的jQuery插件,但仍未成功。 任何想法?

为什么不这样做:

仅将文本内容移至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;

确定不是那么简单,需要大量的JavaScript代码。 所以,最后我使用了Marijn Haverbeke(https://github.com/marijnh/CodeMirror)的CodeMirror Project

尝试使用此:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM