我正在使用jQuery,并尝试找到一种跨浏览器的方式来获取 s和input框中插入符号的像素坐标,以便可以在该位置周围放置一个绝对定位的div。
是否有一些jQuery插件? 还是JavaScript代码段可以做到这一点?
我一直在寻找用于流星自动完成的textarea插入符号坐标插件,因此我已经评估了GitHub上的所有8个插件。到目前为止,获胜者是Component的textarea-caret职位。
特征
-
像素精度
-
没有任何依赖
-
浏览器兼容性:Chrome,Safari,Firefox(尽管有两个错误),IE9 +;可能有效,但未在Opera,IE8或更旧版本中进行测试
-
支持任何字体系列和大小,以及文本转换
-
文本区域可以具有任意填充或边框
-
不会被文本区域中的水平或垂直滚动??条弄糊涂
-
支持硬返回,制表符(IE上除外)和文本中的连续空格
-
比文本区域中的列长的行上的正确位置
-
包装长字时,在行尾空白处没有"重影"位置
这是一个演示-http://jsfiddle.net/dandv/aFPA7/
怎么运行的
在屏幕外创建镜像,其样式与完全相同。然后,将直到插入号的文本区域的文本复制到div中,并在其后插入。然后,将跨度的文本内容设置为textarea中文本的其余部分,以便忠实地复制人造div中的环绕。
这是保证处理所有与包裹长行有关的边缘情况的唯一方法。 GitHub还使用它来确定其@用户下拉列表的位置。
注意:此答案描述了如何获取文本光标/插入符号的字符坐标。要找到像素坐标,您需要进一步扩展它。
首先要记住的是,光标可以处于三种状态
-
在特定位置的常规插入光标
-
具有一定边界区域的文本选择
-
未激活:textarea没有焦点。尚未使用。
IE模型使用Object document.selection,从中我们可以得到一个TextRange对象,该对象使我们可以访问选择内容以及光标位置。
FF模型/ Opera使用方便的变量[input] .selectionStart和selectionEnd。
两种模型都将常规的ative游标表示为零宽度选择,左边界为游标位置。
如果输入字段没有焦点,您可能会发现两者均未设置。
使用以下代码在当前光标位置插入一段文本,并替换当前选择(如果存在的话),我取得了很好的成功。
根据确切的浏览器,YMMV。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| function insertAtCursor(myField, myValue) {
/* selecion model - ie */
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
/* field.selectionstart/end firefox */
else if (myField.selectionStart || myField.selectionStart == '0' ) {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
myField.focus();
}
// cursor not active/present
else {
myField.value += myValue;
} |
错误提示:链接未在顶部段落中正确标记。
选择对象:http://msdn.microsoft.com/zh-cn/library/ms535869(VS.85).aspx
TextRange对象:http://msdn.microsoft.com/zh-cn/library/ms535872(VS.85).aspx
我不认为可以在所有浏览器中完成。有人在IE6中完成了此操作,但在FF或Opera(AFAIK)中不起作用。也许您可以使其在所有浏览器中正常工作。
这是2005年的博客文章。