在选定值javascript之前和之后设置文本

时间:2016-04-14 11:05:27

标签: javascript

我想在所选文本之前和之后插入值。我在其他答案中找到了这段代码,但它在firefox上没有用。有什么解决方法吗?

function insertHtmlAtSelectionEnd(html, isBefore) {
var sel, range, node;
if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
        range = window.getSelection().getRangeAt(0);
        range.collapse(isBefore);

        // Range.createContextualFragment() would be useful here but was
        // until recently non-standard and not supported in all browsers
        // (IE9, for one)
        var el = document.createElement("div");
        el.innerHTML = html;
        var frag = document.createDocumentFragment(), node, lastNode;
        while ( (node = el.firstChild) ) {
            lastNode = frag.appendChild(node);
        }
        range.insertNode(frag);
    }
} else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    range.collapse(isBefore);
    range.pasteHTML(html);
}
}

在此代码中,当range.collapse设置为true时,如果我们尝试将其设置为false,它仍然是真的。这只发生在firefox.Works中完美的chrome.Any变通方法?

0 个答案:

没有答案