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


当前回答

如果你有访问iframe页面,想要一个不同的CSS应用在它上,只有当你加载它通过iframe在你的页面上,在这里我找到了一个解决方案,这类事情

即使iframe正在加载不同的域,这也是有效的

检查postMessage()

计划是,将CSS作为消息发送到iframe

iframenode.postMessage('h2{color:red;}','*');

*是发送这条消息,不管它在iframe中的哪个域

并在iframe中接收消息,并将接收到的消息(CSS)添加到该文档头。

在iframe页面中添加的代码

window.addEventListener('message',function(e){

    if(e.data == 'send_user_details')
    document.head.appendChild('<style>'+e.data+'</style>');

});

其他回答

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

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

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的内容不完全在您的控制之下,或者您希望以不同的样式访问来自不同页面的内容,您可以尝试使用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);

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

我找到了另一个解决方案,把样式放在主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”标签,这是另一种选择

我认为最简单的方法是添加另一个div,在相同的地方iframe,然后

使它的z-index大于iframe容器,所以你可以很容易地只是样式你自己的div。如果你需要点击它,只需使用指针事件:没有在你自己的div,所以iframe将工作,以防你需要点击它;)

我希望它能帮助到别人;)

如果你有访问iframe页面,想要一个不同的CSS应用在它上,只有当你加载它通过iframe在你的页面上,在这里我找到了一个解决方案,这类事情

即使iframe正在加载不同的域,这也是有效的

检查postMessage()

计划是,将CSS作为消息发送到iframe

iframenode.postMessage('h2{color:red;}','*');

*是发送这条消息,不管它在iframe中的哪个域

并在iframe中接收消息,并将接收到的消息(CSS)添加到该文档头。

在iframe页面中添加的代码

window.addEventListener('message',function(e){

    if(e.data == 'send_user_details')
    document.head.appendChild('<style>'+e.data+'</style>');

});