有没有办法将代码镜像中编写的 css 应用于 iframe 的 html 内容



我有两个代码镜像文本区域,一个用于html,一个用于css。按下按钮时,我想将 html 和 css 输出到 iframe 中。即我想要一些同样粗体的绿色文本。这将由文本区域中编写的 css 和 html 驱动。

我尝试针对iframe的css和html属性,这些属性适用于html,但不适用于css。

  $("#create").click(function () {
        $("#iframe").contents().find("body").html("");
        var htmlEditor = $('.CodeMirror')[0].CodeMirror;
        var cssEditor = $('.CodeMirror')[2].CodeMirror;
        $("#iframe").contents().find("body").html(htmlEditor.getValue());
        $("#iframe").contents().find("body").css(cssEditor.getValue());
    });

数组中的位置 1 还有一个 JavaScript 编辑器,用于页面上的代码镜像,但这是另一个问题。

https://i.stack.imgur.com/NkI8D.jpg

正如您从我第一次尝试中看到的那样,文本显示为粗体,但粗体标签没有对其应用 CSS 修改。我觉得我不了解 iframe 以及它如何正常工作。我尝试将类应用于标签,但没有结果。

我找到的解决方案是将要应用的cs附加到头部

$('#iframe').contents().find("head").append($("<style type='text/css'>" + cssEditor.getValue() + "</style>"));

如果有人有任何更好的解决方案,请发布我会非常感兴趣!

最新更新