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


当前回答

下面是如何直接应用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的内容。我的建议是使用服务器端脚本(PHP、ASP或Perl脚本),或者找到可以将提要转换为JavaScript代码的在线服务。唯一的另一种方法是如果你能做一个服务器端包含。

iframe被大多数浏览器像处理一个不同的HTML页面一样处理。如果希望对iframe的内容应用相同的样式表,只需从其中使用的页面引用它。

我遇到了谷歌日历这个问题。我想用更暗的背景和改变字体。

幸运的是,来自嵌入代码的URL对直接访问没有限制,因此通过使用PHP函数file_get_contents可以获得 来自页面的全部内容。而不是调用谷歌URL,可以调用位于您的服务器上的php文件,例如Google .php,它将包含修改的原始内容:

$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');

将路径添加到样式表:

$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);

(这将把样式表放在头结束标记之前的最后。)

在css和js被相对调用的情况下,从原始url中指定基url:

$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);

最终的google.php文件应该是这样的:

<?php
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
echo $content;

然后将iframe嵌入代码更改为:

<iframe src="http://www.yourwebsiteurl.com/google.php" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></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>');

});