[英]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.