HTML - 隐藏一个 iframe

44

我如何隐藏一个iframe,但仍然加载它?例如:播放 YouTube 歌曲。

<iframe src="https://www.youtube.com/embed/X18mUlDddCc?autoplay=1" style="display: none;"></iframe>

这将隐藏iframe,但似乎没有加载iframe。(歌曲没有播放。)

谢谢


请在样式中使用宽度为0! - YOU
是的,因为视频不会自动播放。这是一种不好的做法,你完全错误地使用YouTube视频来播放歌曲,你知道YouTube通常会播放商业广告吗?你的访问者怎么关闭它呢?但我至少编辑了这里的一个答案,以便在上下文中回答你。 - JGallardo
在最新版本的Chrome中,已禁用iframes中的?autoplay=1,因此此问题和答案不再相关。 - Lime
8个回答

38

你可以使用 width: 0; height: 0; position: absolute; 和 border: 0; 来实现。

所以更新后的代码将是这样的!

<iframe src="https://www.youtube.com/embed/X18mUlDddCc?autoplay=1" style="position: absolute;width:0;height:0;border:0;"></iframe>

新增:

style="position: absolute; width:0; height:0; border:0;"

它将隐藏该元素,使媒体在后台播放,并且还会折叠它所占用的空间!

更新 Fiddle:

http://jsfiddle.net/ygkvbphs/


你能否请详细解释一下这个? - JGallardo
小点是问题所在。 - user3854743
2
如果我编辑这个 fiddle 并在它上面和下面添加一个元素,我可以看到这个 iframe 占据空间。 - Dan But
如果你有 border: none,你就不需要 border: 0,因为 0 会被 none 覆盖。 - jcubic
已更新以解决间距问题。@DanBut - YOU
显示剩余2条评论

14

在添加了绝对定位之前,我仍然无法解决 iframe 占用空间的问题。添加了绝对定位后,它完全不再占用空间。

<iframe src="/auth/sso/" style="width: 0; height: 0; border: 0; border: none; position: absolute;"></iframe>


这是胜利的答案。position: absolute; 使一切都有所不同。 - GTS Joe

7

将可见性设置为隐藏。但是它占用的空间不会折叠。

<iframe src="https://www.youtube.com/embed/X18mUlDddCc?autoplay=1" style="visibility: hidden;"></iframe>

7
现有的使用CSS的答案对我不起作用。即使使用display:none,我最终还是得到了一个4x4点的iframe位置。我需要做的是以下内容:
<iframe width="0" height="0" frameborder="0" src="https://www.youtube.com/embed/X18mUlDddCc?autoplay=1"></iframe> 

2
通过结合两种方法,我使用了height:0;visibility:0,因为这可以隐藏任何边框或者盒子阴影。

2

只需设置style"display: none;"


<iframe src="your url" style="display: none;"></iframe> 

0

您可以使用CSS将iframe定位到页面之外,这样就不会留下任何痕迹。

<iframe style="position: absolute; left: -900000px" src="https://www.youtube.com/embed/X18mUlDddCc?autoplay=1"></iframe> 

0

从 iframe 中移除 src,然后再添加回去 - 强制加载 iframe:

 /**
 * Issue: iframe doesn't show because it's in a div that is display:none on load
 *
 * Solution: When the button is clicked to show the hidden div:
 *           in the iframe, copy the url from the src attribute
 *           then set the src attribute to ""
 *           then set the src attribute back to its original value.
 *           This forces the iframe to load.
 */

$('#show-div-button').click(function() {

    var iframe = $('iframe');
    var iframe_src = iframe.attr('src');

    iframe.attr('src', '');
    iframe.attr('src', iframe_src);
});

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