我有一个简单的页面,有一些iframe部分(显示RSS链接)。如何将相同的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页面,想要一个不同的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>');

});

可以试试这个:

$('iframe').load( function() {
     $('iframe').contents().find("head")
     .append($("<style type='text/css'>  .my-class{display:none;}  </style>"));
  });

当你说“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();

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

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

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>
..........

这里的其他答案似乎使用了jQuery和CSS链接。

这段代码使用了普通JavaScript。它创建了一个新的<style>元素。它将该元素的文本内容设置为包含新CSS的字符串。它将该元素直接追加到iframe文档的头部。

var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
  '.some-class-name {' +
  '  some-style-name: some-value;' +
  '}' 
;
iframe.contentDocument.head.appendChild(style);