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


当前回答

在定义域内有两个东西

iFrame节 在iFrame内加载

所以你想要像这样设置这两个部分,

1. iFrame部分的样式

它可以使用带有受尊重的id或类名的CSS样式。你也可以在父样式表中设置它的样式。

<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>

<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>

2. 样式页面加载在iFrame内

这个样式可以在Javascript的帮助下从父页面加载

var cssFile  = document.createElement("link") 
cssFile.rel  = "stylesheet"; 
cssFile.type = "text/css"; 
cssFile.href = "iFramePage.css"; 

然后将该CSS文件设置为受尊重的iFrame部分

//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile); 
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);

在这里,你也可以用这种方式编辑iFrame内的页面头部部分

var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
   $("<link/>",{ 
      rel: "stylesheet", 
      href: urlPath, 
      type: "text/css" }
     ));

其他回答

扩展上面的jQuery解决方案来处理加载帧内容的延迟。

$('iframe').each(function(){
    function injectCSS(){
        $iframe.contents().find('head').append(
            $('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })
        );
    }

    var $iframe = $(this);
    $iframe.on('load', injectCSS);
    injectCSS();
});
var $head = $("#eFormIFrame").contents().find("head");

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

如果你有访问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>');

});

如果你想从主页重用CSS和JavaScript,也许你应该考虑用Ajax加载的内容替换<IFRAME>。当搜索机器人能够执行JavaScript时,这对SEO更加友好。

这是一个jQuery的例子,包括另一个html页面到您的文档。这比iframe更有利于搜索引擎优化。为了确保机器人没有索引所包含的页面,只需在robots.txt中将其添加为禁止

<html>
  <header>
    <script src="/js/jquery.js" type="text/javascript"></script>
  </header>
  <body>
    <div id='include-from-outside'></div>
    <script type='text/javascript'>
      $('#include-from-outside').load('http://example.com/included.html');
    </script> 
  </body>
</html>

你也可以直接从谷歌:http://code.google.com/apis/ajaxlibs/documentation/中包含jQuery——这意味着可选的自动包含新版本和一些显著的速度提升。同时,这意味着你必须相信他们交付给你的只是jQuery;)

可以试试这个:

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