我正在开发我的 WYSIWYG 编辑器。我有这样的代码:
doc.execCommand(cmd, false, null);
cmd 参数将是“粗体”、“斜体”等。doc 变量引用 iframe 中的文档,它在其他地方初始化:
doc = iframe1.contentWindow.document;
它在 Chrome 中运行良好,但在 IE 中(我的是 IE9)根本不起作用。
我用开发者工具调试了我的代码,没有发现任何问题,只是 execCommand 函数不起作用。
我已经通过 Internet 进行了搜索,但找不到可用的解决方案。
有人愿意帮我吗?
代码示例:
function $see(e, o) {
var that = this;
...
this.e = $see.make('iframe', { 'class': 'editor' }); // editor iframe
this.e.onload = function () { // call when the document is loaded
var d = that.e.contentWindow || that.e.contentDocument;
if (d.document) d = d.document;
that.doc = d;
that.doc.write('<html><head></head><body></body></html>');
that.doc.body.innerHTML = that.ta.value; // that.ta refers to an textarea
that.doc.body.setAttribute('contenteditable', 'true');
...
};
}
$see.prototype.exec = function (cmd) {
// call in an <a> tag's onclick event outside the iframe
this.doc.execCommand(cmd, false, null);
};
最佳答案
那是因为在不同的浏览器中使用 iframe 的方法不同
这是它应该如何工作
var doc= iframe1.contentWindow || iframe1.contentDocument;
if (doc.document)
doc=doc.document;
更新
好吧,我想我犯了一个小错误,它应该是这样的:
var doc = iframe.contentWindow || iframe.contentDocument.defaultView;
if (doc.document)
doc=doc.document;
关于javascript - iframe 中的 document.execCommand 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6463618/