如何得到光标在文本区域中的位置?

我有一个文本区域,我想知道,如果我是在最后一行的文本区域或第一行的文本区域与我的光标与 JavaScript。

我想抓取第一个换行符和最后一个换行符的位置,然后抓取光标的位置。

var firstNewline = $('#myTextarea').val().indexOf('\n');
var lastNewline = $('#myTextarea').val().lastIndexOf('\n');


var cursorPosition = ?????;


if (cursorPosition < firstNewline)
// I am on first line.
else if (cursorPosition > lastNewline)
// I am on last line.
  • 是否有可能在文本区域内获取光标位置?
  • 你有更好的建议来确定我是在文本区域的第一行还是最后一行?

JQuery 解决方案是首选,除非 JavaScript 同样简单或更简单。

162530 次浏览

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.

Here's a cross browser function I have in my standard library:

function getCursorPos(input) {
if ("selectionStart" in input && document.activeElement == input) {
return {
start: input.selectionStart,
end: input.selectionEnd
};
}
else if (input.createTextRange) {
var sel = document.selection.createRange();
if (sel.parentElement() === input) {
var rng = input.createTextRange();
rng.moveToBookmark(sel.getBookmark());
for (var len = 0;
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
len++;
}
rng.setEndPoint("StartToStart", input.createTextRange());
for (var pos = { start: 0, end: len };
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
pos.start++;
pos.end++;
}
return pos;
}
}
return -1;
}

Use it in your code like this:

var cursorPosition = getCursorPos($('#myTextarea')[0])

Here's its complementary function:

function setCursorPos(input, start, end) {
if (arguments.length < 3) end = start;
if ("selectionStart" in input) {
setTimeout(function() {
input.selectionStart = start;
input.selectionEnd = end;
}, 1);
}
else if (input.createTextRange) {
var rng = input.createTextRange();
rng.moveStart("character", start);
rng.collapse();
rng.moveEnd("character", end - start);
rng.select();
}
}

http://jsfiddle.net/gilly3/6SUN8/

Here is code to get line number and column position

function getLineNumber(tArea) {


return tArea.value.substr(0, tArea.selectionStart).split("\n").length;
}


function getCursorPos() {
var me = $("textarea[name='documenttext']")[0];
var el = $(me).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
var ret = pos - prevLine(me);
alert(ret);


return ret;
}


function prevLine(me) {
var lineArr = me.value.substr(0, me.selectionStart).split("\n");


var numChars = 0;


for (var i = 0; i < lineArr.length-1; i++) {
numChars += lineArr[i].length+1;
}


return numChars;
}

tArea is the text area DOM element