How to apply CSS to iframe?

2018-12-31 00:02发布

I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?

标签: html css iframe
26条回答
其实,你不懂
2楼-- · 2018-12-31 00:07

The following worked for me.

var iframe = top.frames[name].document;
var css = '' +
          '<style type="text/css">' +
          'body{margin:0;padding:0;background:transparent}' +
          '</style>';
iframe.open();
iframe.write(css);
iframe.close();
查看更多
十年一品温如言
3楼-- · 2018-12-31 00:08

There is a wonderful script that replaces a node with an iframe version of itself. CodePen Demo

enter image description here

Usage Examples:

// Single node
var component = document.querySelector('.component');
var iframe = iframify(component);

// Collection of nodes
var components = document.querySelectorAll('.component');
var iframes = Array.prototype.map.call(components, function (component) {
  return iframify(component, {});
});

// With options
var component = document.querySelector('.component');
var iframe = iframify(component, {
  headExtra: '<style>.component { color: red; }</style>',
  metaViewport: '<meta name="viewport" content="width=device-width">'
});
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 00:10

Edit: This does not work cross domain unless the appropriate CORS header is set.

There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:

<iframe name="iframe1" id="iframe1" src="empty.htm" 
        frameborder="0" border="0" cellspacing="0"
        style="border-style: none;width: 100%; height: 120px;"></iframe>

The style of the page embedded in the iframe must be either set by including it in the child page:

<link type="text/css" rel="Stylesheet" href="Style/simple.css" />

Or it can be loaded from the parent page with Javascript:

var cssLink = document.createElement("link");
cssLink.href = "style.css"; 
cssLink.rel = "stylesheet"; 
cssLink.type = "text/css"; 
frames['iframe1'].document.head.appendChild(cssLink);
查看更多
旧时光的记忆
5楼-- · 2018-12-31 00:13

As an alternative, you can use CSS-in-JS technology, like below lib:

https://github.com/cssobj/cssobj

It can inject JS object as CSS to iframe, dynamically

查看更多
公子世无双
6楼-- · 2018-12-31 00:15
var $head = $("#eFormIFrame").contents().find("head");

$head.append($("<link/>", {
    rel: "stylesheet",
    href: url,
    type: "text/css"
}));
查看更多
余生无你
7楼-- · 2018-12-31 00:15

var link1 = document.createElement('link');
    link1.type = 'text/css';
    link1.rel = 'stylesheet';
    link1.href = "../../assets/css/normalize.css";
window.frames['richTextField'].document.body.appendChild(link1);

查看更多
登录 后发表回答