嵌入YouTube视频IFrame并实现响应式布局

7
我在一个Magento网站上嵌入了以下链接的YouTube视频(除非有我不知道的插件,否则Magento并不重要)。
<iframe width="640" height="360" src="http://www.youtube.com/embed/Zq-805aUM7M?feature=player_embedded" frameborder="0" allowfullscreen></iframe>

我认为这段代码不好,因为它不具有响应式的特性。如何解决?


只是一个建议:http://getbootstrap.com/components/#responsive-embed 你只需要响应式嵌入的CSS。 - nstungcom
8个回答

8

尝试纯CSS方式:

iframe, object, embed {
        max-width: 100%;
        max-height: 100%;
}

如果那不起作用,请尝试这个: https://benmarshall.me/responsive-iframes/
该链接涉及到响应式 iframe 的技术。

我会尝试,但请注意我仍希望默认情况下宽度为“640”高度为“360”。 - user829174
(注意)如果用于WordPress文章,您可以在单个文章中仅使用.entry-content iframe、.entry-content object、.entry-content embed替换这些标记。 - chenghuayang

3
我认为这是最好的方法来完成它。

.youtube-video {
  width: 100%;
  aspect-ratio: 16/9;
}
<iframe class="youtube-video" src="<YOUR_YOUTUBE_VIDEO_URL>" frameborder="0"></iframe>

还需要在这里查看aspect-ratio的浏览器兼容性。


1
这对我来说似乎是最干净的解决方案。不需要使用绝对位置的奇怪技巧。 - Maharkus

2
为了特定地针对YouTube视频,而不是所有的iframe或embed对象,您可以使用基于在src中出现的字符串的属性选择器。
iframe[src*=youtube]
{
  max-width:100%;
  height:100%;
}

这对我很有帮助,但无论如何,这里可以找到更多解决方案,适用于其他(特定)情况。

1

网上有很多提示建议删除“width”和“height”属性,但在某些情况下这是不可能的。但用户可以使用CSS覆盖这些属性。

.wrapper {
    position: relative;
    height: 0;
    overflow: hidden;
    padding-bottom: 56.25%; }

还有 iframe:

.wrapper iframe[width][height] {
    position: absolute;
    top: 0;
    left: 0;
    width: 100% !important;
    height: 100% !important; }

请注意CSS选择器中的[width]和[height]以及"!important"指令,这些对于覆盖iframe的宽度和高度属性值是必不可少的。

0
我最终得到了这个结果,它将所有的 iframe 元素转换为 16:9:
<style>
.youtube-container {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%;
}
.youtube-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 0;
}
</style>

<iframe src="https://www.youtube.com/watch?v=oTLZci5dp44"></iframe>

<script>
$('iframe[src*="youtube"]').wrap('<div class="youtube-container"></div>');
</script>

0
我已经为我的未来网站解决了这个问题。这是我的脚本,不知道你觉得怎么样。它应该适用于任何提供商(youtube、vimeo等),保留原始纵横比,并且只要在更新页面后运行videoIframe_MakeResponsive('youtube','16/9'),就可以与任何附加的对象一起使用。如果没有指定宽度/高度,则'16/9'是默认的纵横比。希望这可以帮到你!

// Greatest Common Divisor
function Math_gcd(a, b) {
    if (a<b)
        [a, b] = [b, a]
    return b ? Math_gcd(b, a%b) : a
}

// get ratio ('16/9' or something) from dimensions
function Math_ratio(width, height) {
    const gcd = Math_gcd(width, height)
    return width/gcd + '/' + height/gcd
}

// add multiple css properties
function css(element, jsonCSS) {
    for (const property in jsonCSS)
        element.style[property] = jsonCSS[property]
}

// autorun
function autorun(callback) {
    if (document.readyState != 'loading')
        callback()
    else
        document.addEventListener('DOMContentLoaded', callback)
}

// responsive iframe
function videoIframe_MakeResponsive(provider, defaultRatio = '16/9') {
    document.querySelectorAll('iframe[src*="' + provider + '"]').forEach(iframe => {
        if (!iframe.classList.contains('videoIframeFixed')) { // fix only new iframes
            let width = iframe.getAttribute('width')
            let height = iframe.getAttribute('height')
            let aspectratio = (width && height) ? Math_ratio(width, height) : defaultRatio
            iframe.removeAttribute('width') // reset
            iframe.removeAttribute('height') // reset
            iframe.classList.add('videoIframeFixed') // for future reference
            // wrapper container
            let wrapper = document.createElement('div')
            iframe.parentNode.insertBefore(wrapper, iframe)
            wrapper.appendChild(iframe) // move iframe inside
            // style
            css(wrapper, {
                'width': '100%',
                'position': 'relative',
                'aspect-ratio': aspectratio
            })
            css(iframe, {
                'width': '100%',
                'height': '100%',
                'position': 'absolute'
            })
        }
    })
}

// run it on page load
autorun(function () {
    videoIframe_MakeResponsive('youtube')
    videoIframe_MakeResponsive('vimeo')
    /* ... etc ... */
})


0

我尝试过,但没有一个是真正响应式的。所以我使用了以下的iframe和CSS。

HTML:

    <iframe class="video-container"  src="https://www.youtube.com/embed/-H2mmm5pMmY" frameborder="0" allow="accelerometer; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>


CSS:
.video-container {
position:relative;
height:22em;
width:-webkit-fill-available;
overflow:hidden;
}

.video-container iframe, .video-container object, .video-container embed {
position:relative;
top:0;
left:0;
width:100%;
height:100%;
}

-1

首先,设置iframe的宽度和高度以匹配您的比例 - 对我而言是16比9:

<figure>
    <iframe class="youtube-video" width="640" height="360" src="..." allowfullscreen></iframe>
</figure>
<script>
    $(function(){
        var
            $allVideos = $("iframe[src*='//player.vimeo.com'], iframe[src*='//www.youtube.com'], object, embed")
            ,$fluidEl = $("figure")
        ;
        $allVideos.each(function() {
            $(this).attr('data-aspectRatio', this.height / this.width).removeAttr('height').removeAttr('width');
        });
        $(window).resize(function(){
            var newWidth = $fluidEl.width();
            $allVideos.each(function(){
                var $el = $(this);
                $el.width(newWidth).height(newWidth * $el.attr('data-aspectRatio'));
            });
        }).resize();
    });
</script>

Bootstrap 4 的拥有者(可能是更低版本)更加幸运:

<figure class="embed-responsive embed-responsive-16by9">
    <iframe class="youtube-video" width="640" height="360" src="..." allowfullscreen></iframe>
</figure>

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