Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

javascript - execCommand("insertHTML", ...) in Internet Explorer

I'm building a wysiwyg-editor with an editable iframe using document.execCommand(). Now i need to use the "insertHTML" command which works perfectly in Chrome and Firefox but of course it doesn't work in Internet Explorer:

function run() {
  document.getElementById("target").focus();
  document.execCommand("insertHTML", false, "<b>ins</b>");
}
<div contenteditable id="target">contenteditable</div>
<button onclick="run()">contenteditable.focus() + document.execCommand("insertHTML", false, "&lt;b>ins&lt;/b>")</button>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In IE <= 10 you can use the pasteHTML method of the TextRange representing the selection:

var doc = document.getElementById("your_iframe").contentWindow.document;

if (doc.selection && doc.selection.createRange) {
    var range = doc.selection.createRange();
    if (range.pasteHTML) {
        range.pasteHTML("<b>Some bold text</b>");
    }
}

UPDATE

In IE 11, document.selection is gone and insertHTML is still not supported, so you'll need something like the following:

https://stackoverflow.com/a/6691294/96100


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...