簡體   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