IE问题 - 在可编辑的框架中插入html

时间:2014-02-25 16:13:36

标签: jquery internet-explorer wysiwyg designmode

我在这里尝试了一些基本的所见即所得的功能 - http://jsfiddle.net/Q6Jp9/28/

目前,我所要做的就是从" Markup"中获取用户输入。框并将其插入" Visual"单击“可视”按钮时的框。可视框是可编辑的iframe。

我的jsfiddle示例适用于Firefox和Chrome浏览器。在IE9和IE10上,文本出现在第二次尝试。在标记框中键入一些文本后,我第一次单击“可视”按钮时,iframe变为可编辑但没有文本。如果我再次单击Markup然后再单击Visual,我会在那里看到文本。

这是小提琴的javascript部分。

function iframe_load() {
var txtBox = $("#txtMarkup");
var iframe = document.getElementById('iframe');
var contentWindow = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.defaultView;
$(iframe).show();
$("#btnVisual").removeClass("notSelected").addClass("selected");
$("#btnMarkup").removeClass("selected").addClass("notSelected");

if (document.all) { //IE  
    contentWindow.document.designMode = 'On';        
    var range = contentWindow.document.body.createTextRange();
    range.pasteHTML($(txtBox).val());
    range.collapse(false);
    range.select();
    contentWindow.focus();
} else {
    contentWindow.document.designMode = 'On';
    contentWindow.document.execCommand('selectAll', null, null); //Required to prevent appending
    try { //This throws an error in FireFox, but command is successful
        contentWindow.document.execCommand('insertHtml', false, $(txtBox).val());
    } catch (ex) {}
    contentWindow.focus();
}
return false;
}

function iframe_hide() {
var txtBox = $("#txtMarkup");
var iframe = document.getElementById('iframe');

$(txtBox).show();
$(iframe).hide();
$("#btnMarkup").removeClass("notSelected").addClass("selected");
$("#btnVisual").removeClass("selected").addClass("notSelected");

return false;
}

提前致谢!

1 个答案:

答案 0 :(得分:1)

我猜测问题是您可能需要在显示iframe并使其可编辑后等待一段时间。这似乎有效:

演示:http://jsfiddle.net/Q6Jp9/35/

代码:

function iframe_load() {
    var txtBox = $("#txtMarkup");
    var iframe = document.getElementById('iframe');
    var contentWindow = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.defaultView;
    $(iframe).show();
    $("#btnVisual").removeClass("notSelected").addClass("selected");
    $("#btnMarkup").removeClass("selected").addClass("notSelected");

    contentWindow.document.designMode = 'on';

    window.setTimeout(function() {
        var doc = iframe.contentDocument || iframe.contentWindow.document;
        if (doc.body.createTextRange) {
            var range = doc.body.createTextRange();
            range.pasteHTML(txtBox.val());
            range.collapse(false);
            range.select();
            contentWindow.focus();
        } else {
            doc.execCommand('selectAll', null, null); //Required to prevent appending
            doc.execCommand('insertHtml', false, txtBox.val());
        }
        contentWindow.focus();
    }, 20);

    return false;
}