在insertNode by range之后设置可编辑div的光标位置

时间:2014-02-17 06:43:05

标签: javascript selection contenteditable

我在页面中有一个可信的div subscribeTextEditor

并且面板容器有很多图标,可以选择图标并插入到可信的div。

下面的代码不是第一个版本。

在我发现第一个版本在ie8中不起作用后,它被多次修改。

现在,除了插入位置不正确外,此版本最接近工作查找。

我的问题的详细信息显示在下面的代码中。

// below function from
// http://stackoverflow.com/questions/6690752/
// insert-html-at-caret-in-a-contenteditable-div
function insertTextAtCursor(html) {

    // if don't set focus on contenteditable div,
    // this function just work find at the first time. 
    // after first time, its not work anymore
    // and totally not work in ie8
    document.getElementById('subscribeTextEditor').focus();

    // before call this method, everything work fine 
    // but the position of insert icon is incorrect
    // the position is imprecise somehow
    // sometimes at the first position of contenteditable div
    // and somtimes at the next position of previous insert text
    setCursor(subscribeTextEditor, lastCursor);

    var sel, range;
    var text = html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            var el = document.createElement("div");
            el.innerHTML = html;

            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            var firstNode = frag.firstChild;
            range.insertNode(frag);

            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
            lastCursor = range.endOffset;
        }
    } else if (document.selection && document.selection.createRange) {
        // for IE8
        sel = document.selection;
        var originalRange = sel.createRange();
        originalRange.collapse(true);
        sel.createRange().pasteHTML(html);
    }
}

// below function from 
// http://stackoverflow.com/questions/2871081/
// jquery-setting-cursor-position-in-contenteditable-div
function setCursor(node, pos) {
    var node = (typeof node == "string" || node instanceof String) ? document
            .getElementById(node) : node;
    if (!node) {
        return false;
    } else if (node.createTextRange) {
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    } else if (node.setSelectionRange) {
        node.setSelectionRange(pos, pos);
        return true;
    }
    return false;
}

0 个答案:

没有答案