18

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

4

1 回答 1

33

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:

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:

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 Rangy library, which adds a wrapper to IE TextRange object that behaves like a DOM Range. A DOM Range consists 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 article should provide some introduction.

于 2010-02-06T15:02:19.027 回答