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



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

目前,我所要做的就是从"标记"框中获取用户输入,并在单击"可视化"按钮时将其插入到"可视化"框中。视觉框是一个可编辑的iframe。

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

这是fiddle的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;
}

提前感谢!

我想问题是,在显示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;
}

最新更新