Javascript 如何在可编辑的 DIV 中找到光标位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2213376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find cursor position in a contenteditable DIV?
提问by Sharief Shaik
I am writing a autocompleter for a content editable DIV (need to render html content in the text box. So preferred to use contenteditable DIV over TEXTAREA). Now I need to find the cursor position when there is a keyup/keydown/click event in the DIV. So that I can insert the html/text at that position. I am clueless how I can find it by some computation or is there a native browser functionality that would help me find the cursor position in a contententeditable DIV.
我正在为内容可编辑的 DIV 编写一个自动完成程序(需要在文本框中呈现 html 内容。因此首选使用 contenteditable DIV 而不是 TEXTAREA)。现在我需要在 DIV 中有 keyup/keydown/click 事件时找到光标位置。这样我就可以在那个位置插入 html/text。我不知道如何通过一些计算找到它,或者是否有本机浏览器功能可以帮助我在可编辑的 DIV 中找到光标位置。
回答by Tim Down
If all you want to do is insert some content at the cursor, there's no need to find its position explicitly. The following function will insert a DOM node (element or text node) at the cursor position in all the mainstream desktop browsers:
如果您只想在光标处插入一些内容,则无需明确查找其位置。以下函数将在所有主流桌面浏览器的光标位置插入一个 DOM 节点(元素或文本节点):
function insertNodeAtCursor(node) {
var range, html;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
range.insertNode(node);
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
html = (node.nodeType == 3) ? node.data : node.outerHTML;
range.pasteHTML(html);
}
}
If you would rather insert an HTML string:
如果您更愿意插入 HTML 字符串:
function insertHtmlAtCursor(html) {
var range, node;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
}
}
UPDATE
更新
Following the OP's comments, I suggest using my own Rangylibrary, which adds a wrapper to IE TextRangeobject that behaves like a DOM Range. A DOM Rangeconsists of a start and end boundary, each of which is expressed in terms of a node and an offset within that node, and a bunch of methods for manipulating the Range. The MDC articleshould provide some introduction.
按照 OP 的评论,我建议使用我自己的Rangy库,它为 IETextRange对象添加了一个包装器,其行为类似于 DOM Range。甲DOM范围由开始和结束边界,其中的每一个中的节点的术语和该节点内的偏移被表达,和一堆用于操纵范围方法。该MDC文章应该提供一些介绍。

