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


当前回答

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

其他回答

我是这么做的:

Div与类保存iframe 将iframe添加到div中。 在CSS文件中

divClass { width: 500px; height: 500px; }
divClass iframe { width: 100%; height: 100%; }

这在IE 6中有效。应该可以在其他浏览器上运行,请检查!

var link1 = document.createElement('link'); link1。type = 'text/css'; link1。rel =“样式表”; link1。href = "../../assets/css/normalize.css"; 窗口框架[' richTextField ']文件。身体。appendChild (link1);

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

如果你想从主页重用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;)

扩展上面的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();
});