如何得到插入符号列(而不是像素)的位置在一个文本区域,在字符,从一开始?

如何使用 JavaScript 获得 <textarea>中插入符号的位置?

例如: This is| a text

这应该返回 7

如何让它返回光标/选区周围的字符串?

例如: 'This is', '', ' a text'

如果单词“ is”突出显示,那么它将返回 'This ', 'is', ' a text'

167463 次浏览

对于 Firefox,Safari (以及其他基于 Gecko 的浏览器) ,你可以很容易地使用 textarea.selectionStart,但是对于 IE 来说,这不起作用,所以你必须这样做:

function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}


var c = "\001",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;


dul.moveToElementText(node);
sel.text = c;
len = dul.text.indexOf(c);
sel.moveStart('character',-1);
sel.text = "";
return len;
}

(完整代码)

我还建议您检查 jQuery 字段选择插件,它允许您这样做和更多..。

编辑: 我实际上重新实现了上面的代码:

function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();


var r = document.selection.createRange();
if (r == null) {
return 0;
}


var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);


return rc.text.length;
}
return 0;
}

检查一个例子 给你

我修改了上面的函数来考虑 IE 中的回车。它没有经过测试,但是我在代码中对它做了类似的处理,所以它应该是可行的。

function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();


var r = document.selection.createRange();
if (r == null) {
return 0;
}


var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);


var add_newlines = 0;
for (var i=0; i<rc.text.length; i++) {
if (rc.text.substr(i, 2) == '\r\n') {
add_newlines += 2;
i++;
}
}


//return rc.text.length + add_newlines;


//We need to substract the no. of lines
return rc.text.length - add_newlines;
}
return 0;
}

2010年9月5日更新

看到每个人似乎都得到了这个问题的指导,我把我的答案添加到一个类似的问题,其中包含了相同的代码作为这个答案,但是对于那些感兴趣的人有完整的背景:

IE 的 document.selection.createRange 不包括前导或后面的空白行

在 IE 中解释尾行分隔是很棘手的,我还没有看到任何正确的解决方案,包括这个问题的任何其他答案。但是,可以使用以下函数,它将返回 <textarea>或文本 <input>中所选内容的开始和结束(插入符号的情况也是如此)。

注意,textarea 必须有焦点,这个函数才能在 IE 中正常工作。如果有疑问,首先调用 textarea 的 focus()方法。

function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;


if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();


if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");


// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());


// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);


if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;


if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}


return {
start: start,
end: end
};
}

如果你不需要支持 IE,你可以使用 textareaselectionStartselectionEnd属性。

要获得插入符号的位置,只需使用 selectionStart:

function getCaretPosition(textarea) {
return textarea.selectionStart
}

若要获取围绕所选内容的字符串,请使用以下代码:

function getSurroundingSelection(textarea) {
return [textarea.value.substring(0, textarea.selectionStart)
,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
}

JSFiddle 演示。

参见 HTMLTextAreaElement 文档