简体   繁体   中英

Issue with document.execCommand in IE

I am using a html editor and wanted to extend feature to insert html controls at cursor position.

The code i am using is:

document.execCommand("insertHTML", false, "<input type=\"text\">") 

This code works fine Chrome and FF but have issue in IE. It simply doesn't work and throws "invalid argument" error. I have tried the following code:

if (document.selection && document.selection.createRange) {
     range = document.selection.createRange();
     range.collapse(false);
     range.pasteHTML(value);
}

but the textbox add to top of the document and not inside the html editor.

I need help on this. Thanks in advance.

It looks like you're mixing and matching IE and Modern browser standards in that method. I'm not sure it works the way you think it does. Try a little console.log() for firefox or alert() to see which browsers actually enter that method :)

There is no document.selection in Firefox. It's window.getSelection() instead:

Try playing around with the following. Should work in both browsers

if (document.createRange) { // "Standards" :)
    var selection = window.getSelection();

    if (selection.rangeCount > 0) {
        selRange = selection.getRangeAt(0);
        var node = document.createTextNode(stringValue);
        selRange.insertNode(node);
        selRange.setStartAfter(node);
        selection.removeAllRanges();
        selection.addRange(selRange);
    }

} else if (document.selection) { // fallback for IE6-8
    selRange = document.selection.createRange();

    selRange.select();
    selRange.pasteHTML(stringValue);
}

If you encapsulate that in a method and pass "stringValue" you can insert text anywhere.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM