如何将CSS应用于iframe?

html HTML

西里神奇

2020-03-15

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

第1627篇《如何将CSS应用于iframe?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
Harry凯 2020.03.15

Well, I have followed these steps:

  1. Div with a class to hold iframe
  2. Add iframe to the div.
  3. In CSS file,
divClass { width: 500px; height: 500px; }
divClass iframe { width: 100%; height: 100%; }

This works in IE 6. Should work in other browsers, do check!

Pro猪猪 2020.03.15

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

老丝卡卡西西里 2020.03.15

I think the easiest way is to add another div, in the same place as the iframe, then

make its z-index bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use pointer-events:none on your own div, so the iframe would be working in case you need to click on it ;)

I hope It will help someone ;)

A达蒙 2020.03.15

You will not be able to style the contents of the iframe this way. My suggestion would be to use serverside scripting (PHP, ASP, or a Perl script) or find an online service that will convert a feed to JavaScript code. The only other way to do it would be if you can do a serverside include.

路易小卤蛋 2020.03.15

If you control the page in the iframe, as hangy said, the easiest approach is to create a shared CSS file with common styles, then just link to it from your html pages.

Otherwise it is unlikely you will be able to dynamically change the style of a page from an external page in your iframe. This is because browsers have tightened the security on cross frame dom scripting due to possible misuse for spoofing and other hacks.

This tutorial may provide you with more information on scripting iframes in general. About cross frame scripting explains the security restrictions from the IE perspective.

神无Sam乐 2020.03.15

大多数浏览器普遍将iframe视为不同的HTML页面。如果要将相同的样式表应用于iframe的内容,只需从那里使用的页面引用它即可。

梅十三Near 2020.03.15
var $head = $("#eFormIFrame").contents().find("head");

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android