我有一个简单的页面,有一些iframe部分(显示RSS链接)。如何将相同的CSS格式从主页应用到iframe中显示的页面?


当前回答

当你说“doc.open()”这意味着你可以在iframe里面写任何HTML标签,所以你应该为HTML页面写所有的基本标签,如果你想在你的iframe头部有一个CSS链接,就写一个iframe里面有CSS链接。我给你们举个例子:

doc.open();

doc.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><meta http-quiv="Content-Type" content="text/html; charset=utf-8"/><title>Print Frame</title><link rel="stylesheet" type="text/css" href="/css/print.css"/></head><body><table id="' + gridId + 'Printable' + '" class="print" >' + out + '</table></body></html>');

doc.close();

其他回答

如果您在iframe中控制页面,如hangy所说,最简单的方法是创建一个具有通用样式的共享CSS文件,然后只需从html页面链接到它。

否则,您不太可能从iframe中的外部页面动态更改页面的样式。这是因为浏览器已经加强了跨帧dom脚本的安全性,因为可能会滥用欺骗和其他黑客行为。

本教程可能会为您提供更多关于编写iframe脚本的信息。关于跨框架脚本从IE的角度解释了安全限制。

下面的方法对我很有效。

var iframe = top.frames[name].document;
var css = '' +
          '<style type="text/css">' +
          'body{margin:0;padding:0;background:transparent}' +
          '</style>';
iframe.open();
iframe.write(css);
iframe.close();

有一个很棒的脚本可以用节点本身的iframe版本替换节点。 CodePen演示

使用例子:

// Single node
var component = document.querySelector('.component');
var iframe = iframify(component);

// Collection of nodes
var components = document.querySelectorAll('.component');
var iframes = Array.prototype.map.call(components, function (component) {
  return iframify(component, {});
});

// With options
var component = document.querySelector('.component');
var iframe = iframify(component, {
  headExtra: '<style>.component { color: red; }</style>',
  metaViewport: '<meta name="viewport" content="width=device-width">'
});

我是这么做的:

Div与类保存iframe 将iframe添加到div中。 在CSS文件中

divClass { width: 500px; height: 500px; }
divClass iframe { width: 100%; height: 100%; }

这在IE 6中有效。应该可以在其他浏览器上运行,请检查!

我们可以在iframe中插入样式标签。

<style type="text/css" id="cssID">
.className
{
    background-color: red;
}
</style>

<iframe id="iFrameID"></iframe>

<script type="text/javascript">
    $(function () {
        $("#iFrameID").contents().find("head")[0].appendChild(cssID);
        //Or $("#iFrameID").contents().find("head")[0].appendChild($('#cssID')[0]);
    });
</script>