问题
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