javascript - 将 iFrame 源代码与 textarea 元素同步

标签 javascript html

我正在为我自己的内容管理系统 (CMS) 开发纯 JavaScript 所见即所得编辑器。我需要做的是将 IFRAME 中的源代码与 TEXTAREA 元素的内容同步,这样我就可以切换源代码 View 和富文本编辑来回切换。我有一些代码,它同步数据,但是我只能更改富文本编辑器 (IFRAME) 中的内容,而不能更改源代码编辑器 (TEXTAREA) 中的内容。这样做的目的是通过 POST 表单将数据提交到服务器,因为我不知道我还能怎么做。我也不想使用 jQuery。我不是“JavaScript 专家”。无论如何,这是我的代码部分:

<iframe id="editor" frameborder="0"></iframe>
<textarea id="html" onchange="document.getElementById('editor').contentWindow.document.body.innerHTML=this.value;"></textarea>
<script>
var e = document.getElementById("editor").contentWindow;
e.document.designMode = "on";
e.document.open();
e.document.write("<head><style>body{font-family:arial,helvetica,sans-serif;}</style></head>");
e.document.close();

function def() {
   document.getElementById("fontName").selectedIndex = 0;
   document.getElementById("fontSize").selectedIndex = 1;
   document.getElementById("foreColor").selectedIndex = 0;
}

function edit(x, y) {
   e.document.execCommand(x, false, y);
   e.focus();
}

setInterval(function() {
    document.getElementById("html").value = e.document.body.innerHTML;
}, 200);
</script>

最佳答案

弄清楚了,希望这对其他人有帮助;)

<iframe id="editor" frameborder="0">test</iframe>
<textarea id="html" onfocus="editor.rte();" onblur="editor.source();"></textarea>
<script>
<!--
//<![CDATA[
var editor = function() {
    var e = document.getElementById("editor").contentWindow;
    e.document.designMode = "on";
    e.document.open();
    e.document.write("<head><style>body{font-family:arial,helvetica,sans-serif;}</style></head>");
    e.document.close();
    var a, b;
    return {
        run:function(c, s) {
            e.document.execCommand(c, false, s);
        },
        source:function() {
            clearInterval(b);
            a = setInterval(function(){document.getElementById("html").value = e.document.body.innerHTML;}, 200);
        },
        rte:function() {
            clearInterval(a);
            b = setInterval(function(){e.document.body.innerHTML = document.getElementById("html").value;}, 200);
        }
    };
}();
editor.source();
//]]>
-->
</script>

关于javascript - 将 iFrame 源代码与 textarea 元素同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12828211/

相关文章:

html - 如何在django中显示编辑后的头像

html - 具有最大宽度和粘贴图像/文本的网格

javascript - AWS API Gateway JS SDK获取HTTP响应代码

javascript - Jquery UI 日期选择器日期格式

c++ - windows/osx/ipad 上的跨平台 GUI

javascript - 应用程序性能缓慢

mySQL 表 : FROM_UNIXTIME and INTO OUTFILE issues 上的 PHP 脚本

javascript - 确定 DataTables 是否在 1.10 版本中完成。有回调吗?

javascript - 在Web Worker中导入经典脚本和模块

javascript - 清除值时将输入背景颜色返回到原始状态