我有一个 iframe
,我在运行时填充了它的 src
:
$(iframe).attr("src", "<my html page uri>");
其次是:
$(iframe).load(function() {
//Copy style from parent
if (setStyles) {
setStyles = false;
var linkTags = window.parent.document.head.getElementsByTagName("link");
for (var i = 0; i < linkTags.length; i++) {
if (linkTags[i].rel === "stylesheet") {
var node = linkTags[i].cloneNode();
node.href = linkTags[i].href;
this.contentDocument.head.appendChild(node);
}
}
}
//add some elements dynamically
var windowHeight = iframe.contentWindow.document.body.scrollHeight;
$(iframe).height(windowHeight + 'px');
});
在我附加了一些元素后,最后两行代码用于调整框架的大小以适应其内容。
这可行,但问题是我动态添加的 CSS 调整了一些元素的大小,这意味着框架的高度又是错误的。
我是否需要链接动态 CSS 添加和框架的大小调整,以便在调整大小之前将 CSS 应用于元素?
如果可以,怎么做? 谢谢
最佳答案
在读取 scrollHeight 属性之前,您必须等到 CSS 文件加载完毕。要实现它,您可以在调用 appendChild 之前向链接节点添加一个 onload 事件处理程序。
$(node).load(function() {
var windowHeight = iframe.contentWindow.document.body.scrollHeight;
$(iframe).height(windowHeight + 'px');
} ) ;
// Before this:
this.contentDocument.head.appendChild(node);
关于javascript - 动态插入的 CSS(通过链接)在框架加载后应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38822041/