如何从一开始就以字符为单位获取文本区域中插入符号列(而不是像素)的位置? [英] How to get the caret column (not pixels) position in a textarea, in characters, from the start?
问题描述
如何使用 JavaScript 在 中获取插入符号位置?
How do you get the caret position in a <textarea>
using JavaScript?
例如:这是|一段文字
这应该返回 7
.
如何让它返回光标/选择周围的字符串?
How would you get it to return the strings surrounding the cursor / selection?
例如:'This is', '', ' a text'
.
如果突出显示单词is",则返回'This', 'is', 'a text'
.
If the word "is" is highlighted, then it would return 'This ', 'is', ' a text'
.
推荐答案
使用 Firefox、Safari(和其他基于 Gecko 的浏览器)您可以轻松使用 textarea.selectionStart,但对于 IE 不起作用,因此您必须做这样的事情:
With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = " 01",
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 FieldSelection 插件,它允许您这样做并且更多...
I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...
我实际上重新实现了上面的代码:
I actually re-implemented the above code:
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;
}
在此处查看示例.
这篇关于如何从一开始就以字符为单位获取文本区域中插入符号列(而不是像素)的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!