简体   繁体   English

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

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

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 (eg after paste text from clipboard) i've tried different jQuery plugins, but still unsuccessfully. 我试图假定\\ n符号的数量与行数相同,但是有时此方法无法正常工作(例如,从剪贴板粘贴文本后),但是我尝试了不同的jQuery插件,但仍未成功。 any idea? 任何想法?

Why not just do this: 为什么不这样做:

Take the text content only up to selectionStart then make it an array by splitting at eol 仅将文本内容移至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;

The descision is not so simple and requieres large amount of javascript code. 确定不是那么简单,需要大量的JavaScript代码。 So, finally i've used CodeMirror Project by Marijn Haverbeke (https://github.com/marijnh/CodeMirror) 所以,最后我使用了Marijn Haverbeke(https://github.com/marijnh/CodeMirror)的CodeMirror Project

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

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

相关问题 如何获得SCEditor文本区域中的当前插入符位置? - How to get current caret position in a SCEditor textarea? 获取文本区域(IE)中的插入符位置 - Get caret position in textarea (IE) Javascript获取输入文字或文本区域中插入符号的绝对位置(以像素为单位) - Javascript get the absolute position (in px) of a caret in a input text or textarea 如何使用JavaScript查找INPUT和TEXTAREA插入位置坐标? - How To Find INPUT And TEXTAREA Caret Position Coordinates Using JavaScript? 如何从一开始就以字符形式在textarea中获取插入符号列(不是像素)的位置? - How to get the caret column (not pixels) position in a textarea, in characters, from the start? 通过JavaScript在textarea中保存和加载插入位置 - Saving and loading the caret position in a textarea via JavaScript 如何在textarea中的当前插入位置插入文本 - How to insert text at the current caret position in a textarea 如何使用Javascript在文本区域中获取键入字母的位置? - How to get the position of a typed letter in a textarea with Javascript? 如何在 Javascript 中恢复插入符号位置? - How to restore caret position in Javascript? 如何从JavaScript的插入位置获取最后的信息? - How To Get Last Word From Caret Position In JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM