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


当前回答

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

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

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

其他回答

var $head = $("#eFormIFrame").contents().find("head");

$head.append($("<link/>", {
    rel: "stylesheet",
    href: url,
    type: "text/css"
}));

有一个很棒的脚本可以用节点本身的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">'
});

下面是如何直接应用CSS代码,而不使用<link>来加载额外的样式表。

var head = jQuery("#iframe").contents().find("head");
var css = '<style type="text/css">' +
          '#banner{display:none}; ' +
          '</style>';
jQuery(head).append(css);

这将在iframe页面中隐藏横幅。谢谢你的建议!

我找到了另一个解决方案,把样式放在主html像这样

<style id="iframestyle">
    html {
        color: white;
        background: black;
    }
</style>
<style>
    html {
        color: initial;
        background: initial;
    }
    iframe {
        border: none;
    }
</style>

然后在iframe中这样做(参见js的onload)

<iframe  onload="iframe.document.head.appendChild(ifstyle)" name="log" src="/upgrading.log"></iframe>

在js中

<script>
    ifstyle = document.getElementById('iframestyle')
    iframe = top.frames["log"];
</script>

这可能不是最好的解决方案,当然也可以改进,但如果您想在父窗口中保留“style”标签,这是另一种选择

如果iframe的内容不完全在您的控制之下,或者您希望以不同的样式访问来自不同页面的内容,您可以尝试使用JavaScript操作它。

var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);

请注意,根据您使用的浏览器,这可能只适用于来自同一域的页面。