我有一个简单的页面,有一些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版本替换节点。 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页面中隐藏横幅。谢谢你的建议!

这只是一个概念,但是不要在没有安全检查和过滤的情况下实现它!否则脚本可能会攻击您的站点!

答:如果你控制目标站点,你可以像这样设置接收器脚本:

1)使用style参数设置iframe链接,如下:

http://your_site.com/target.php?color=red

(最后一个短语是urlencode函数编码的{color:red}。

2)像这样设置接收页面target.php:

<head>
..........
$col = FILTER_VAR(SANITIZE_STRING, $_GET['color']);
<style>.xyz{color: <?php echo (in_array( $col, ['red','yellow','green'])?  $col : "black") ;?> } </style>
..........

我们可以在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>

这就是我在生产中所做的。值得记住的是,如果iframe属于其他网站,它将触发CORS错误,将无法工作。

    var $iframe =  document.querySelector(`iframe`);
    var doc = $iframe.contentDocument;

    var style = doc.createElement("style");
    style.textContent = `*{display:none!important;}`;
    doc.head.append(style);

在某些情况下,你可能还想给iframe附加一个load事件:

var $iframe =  document.querySelector(`iframe`);

$iframe.addEventListener("load", function() {
    var doc = $iframe.contentDocument;
    var style = doc.createElement("style");
    style.textContent = `*{display:none!important;}`;
    doc.head.append(style);
});