问题描述
如何让 继承其父元素的样式和 javascript.
How do I make an <iframe>
inherit its parent's styles and javascript.
我试过了
var parentHead = $("head", parent.document).html();
$("head").html(parentHead);
但是,它去掉了 标签.此外,我没有看到影响 iframe 的样式.
But, it strips out the <script>
tags.Moreover, I do not see the styles affecting my iframe.
有没有更好的/任何其他我缺少的方法?谢谢.
Is there a better/any other approach to this that I'm missing?Thanks.
推荐答案
您可以通过在 iframe 中包含这样的代码来继承"父级的 CSS:
You can "inherit" the CSS of the parent by having such code in the iframe:
<head>
<script type="text/javascript">
window.onload = function() {
if (parent) {
var oHead = document.getElementsByTagName("head")[0];
var arrStyleSheets = parent.document.getElementsByTagName("style");
for (var i = 0; i < arrStyleSheets.length; i++)
oHead.appendChild(arrStyleSheets[i].cloneNode(true));
}
}
</script>
</head>
在 IE、Chrome 和 Firefox 中对我来说效果很好.
Worked fine for me in IE, Chrome and Firefox.
关于 JavaScript,我找不到直接将父 JavaScript 添加到 iframe 的方法,但是您可以在任何位置添加 parent.
以从父内部使用 JS,例如:
Regarding JavaScript,I couldn't find a way to add the parent JavaScript into the iframe directly, however you can add parent.
anywhere to use the JS from within the parent, for example:
<button type="button" onclick="parent.MyFunc();">Click please</button>
这将在单击按钮时调用父页面中定义的名为 MyFunc
的函数.
This will invoke function called MyFunc
defined in the parent page when the button is clicked.
这篇关于iframe 从父级继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!