Iframe 透明背景

51
我的应用程序有一个带有iframe的模态对话框。我的jQuery代码是这样编写的:当对话框打开时,设置iframe的“src”属性以便内容可以加载。但是,在对话框打开和内容加载之间的延迟期间,iframe 显然会出现为白色方框。我希望iframe具有透明的背景。
我已经尝试在iframe上设置allowtransparency="yes" 。有什么其他想法吗?谢谢!
5个回答

62

我在使用JavaScript创建IFrame时使用了这个方法,它对我有效:

// IFrame points to the IFrame element, obviously
IFrame.src = 'about: blank';
IFrame.style.backgroundColor = "transparent";
IFrame.frameBorder = "0";
IFrame.allowTransparency="true";

不确定是否有任何区别,但我在将IFrame添加到DOM之前设置了这些属性。 添加到DOM后,我将其src设置为真实的URL。


10
+1:直到现在我才知道allowTransparency。谢谢 :) - anon355079
对我来说问题在于我在头部定义了<meta name="color-scheme" content="light dark" />。删除后,Google登录按钮可以在iFrame中很好地显示(即使没有allowTransparency=true)。 - David

43
<style type="text/css">
body {background:none transparent;
}
</style>

如果你将它放在iframe中,那可能会起作用

<iframe src="stuff.htm" allowtransparency="true">

3

将源页面的背景颜色设置为none,并允许iframe元素透明。

源页面(例如,source.html):

<style type="text/css">
    body
    {
        background:none transparent;
    }
</style>

带有iframe的页面:

<iframe src="source.html" allowtransparency="true">Error, iFrame failed to load.</iframe>

1
为什么不直接在屏幕外或隐藏处加载框架,然后在它加载完成后显示。一开始可以显示一个加载图标来向用户提供立即反馈,让用户知道它正在加载。

1
因为没有可靠的方法来知道iframe何时完成加载。Iframe导航是通过设置其“href”属性而不是远程加载来完成的。 - brianjcohen
如果您使用setTimeout在短时间内触发可见性,给帧时间加载的话,可能不是一种解决方案,但是是一种可能的解决方法。 - James Walker

0
你需要让 iframe 的 body 透明。这个方法对我有效:
const iframe = document.createElement( 'iframe' );

iframe.onload = function() {
    const doc = iframe.contentWindow.document,
        head = doc.querySelector( 'head' ),
        style = doc.createElement( 'style' );

        style.setAttribute( 'type', 'text/css' );
        style.innerHTML = 'body { background: transparent!important; }';

        head.appendChild( style );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接