Html 如何通过父窗口 CSS 类将 CSS 应用于内部 Iframe 元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19858217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply CSS to inner Iframe element through parent window CSS class?
提问by Ishan Jain
I have a parent(main) page that has some iframe
sections. And I want to apply css style to inner iframe
element.
我有一个包含一些iframe
部分的父(主)页面。我想将 css 样式应用于内部iframe
元素。
When I googling for it, I found many post relate to this topic but they all suggest to use jquery/javascript to apply CSS to inner elements.
当我搜索它时,我发现很多帖子都与这个主题相关,但他们都建议使用 jquery/javascript 将 CSS 应用于内部元素。
Is it possible to apply css style to inner iframe
element through parent window(main page) CSS class?
是否可以iframe
通过父窗口(主页面)CSS 类将 css 样式应用于内部元素?
(All the iframe
's domain is the same as the parent)
(所有iframe
的域都与父域相同)
回答by himaja
You can not directly apply styles to the inner IFrame element through parent window CSS class even though its domain is same as parent.
您不能通过父窗口 CSS 类直接将样式应用于内部 IFrame 元素,即使其域与父元素相同。
As ,(All the iframe's domain is the same as the parent) ..
As ,(所有 iframe 的域都与父域相同) ..
Best thing you can do is ,to add your main style sheet to the IFrame using javascript or jquery.
您可以做的最好的事情是,使用 javascript 或 jquery 将您的主样式表添加到 IFrame。
$(document).ready(function(){
$('#myIframe').load(function(){
$('#myIframe')
.contents().find("body")
.html("test iframe");
$('#myIframe')
.contents().find("head")
.append($('<link rel="stylesheet" type="text/css" href="style.css">')
);
});
});
回答by gman
If all your CSS is in external files something like this might work in your iframe.
如果您的所有 CSS 都在外部文件中,则这样的内容可能适用于您的 iframe。
<script>
window.onload = function() {
Array.prototype.forEach.call(window.parent.document.querySelectorAll("link[rel=stylesheet]"), function(link) {
var newLink = document.createElement("link");
newLink.rel = link.rel;
newLink.href = link.href;
document.head.appendChild(newLink);
});
};
</script>
It basically asks the parent for all the stylesheets then adds links to the iframe with the same references. If the iframe and the parent page are not at the same location on your server you'd have to manipulate the href
appropriately.
它基本上向父级询问所有样式表,然后使用相同的引用添加指向 iframe 的链接。如果 iframe 和父页面不在服务器上的同一位置,则必须href
适当地操作。
Also the code above probably only works on newer browsers.
此外,上面的代码可能只适用于较新的浏览器。