如何在可疑的DIV中找到光标位置?

Sha*_*aik 17 javascript autocomplete contenteditable cursor-position

我正在为内容可编辑的DIV编写一个自动完成器(需要在文本框中呈现html内容.因此首选使用可信的DIV而不是TEXTAREA).现在我需要在DIV中存在keyup/keydown/click事件时找到光标位置.这样我就可以在那个位置插入html/text.我无法通过某种计算找到它,或者是否有本机浏览器功能可以帮助我找到可信任的DIV中的光标位置.

Tim*_*own 33

如果您只想在光标处插入一些内容,则无需明确找到其位置.以下函数将在所有主流桌面浏览器的光标位置插入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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想要插入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);
    }
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

根据OP的评论,我建议使用我自己的Rangy库,它为IE TextRange对象添加一个行为类似于DOM Range 的包装器.甲DOM范围由开始和结束边界,其中的每一个中的节点的术语和该节点内的偏移被表达,并用于操纵范围一堆方法.该MDC文章应该提供一些介绍.