jquery - 使用 jQuery 按比例调整 iframe 大小以适合 DIV

标签 jquery scale aspect-ratio

我在 div 中有一个视频的 iframe,如下所示:

<div class="media">
    <iframe>
</div>

我在调整窗口大小时动态设置 DIV 的大小。

我想缩放 iframe 以适合 div 内部,同时保持其纵横比。大多数代码都涉及缩放图像,这更容易。

这是我到目前为止所拥有的,但它不起作用:

jQuery.fn.fitToParent = function()
{
    this.each(function()
    {
        var width  = jQuery(this).width();
        var height = jQuery(this).height();
        var parentWidth  = jQuery(this).parent().width();
        var parentHeight = jQuery(this).parent().height();

        if(width < parentWidth)
        {
            newWidth  = parentWidth;
            newHeight = newWidth/width*height;
        }
        else
        {
            newHeight = parentHeight;
            newWidth  = newHeight/height*width;
        }

        jQuery(this).css({
            'height'     :newHeight,
            'width'      :newWidth'
        });
    });
};

基本上,我希望复制“background-size: contains”对 CSS 中的图像执行的大小调整,但对 DIV 中的 iframe 执行的大小调整。

感谢您的帮助!

最佳答案

注意到三个问题:

  1. 您的示例中有一个错误(尾随引号):

    :newWidth'

  2. 您需要设置 iframe 的实际高度和宽度属性,而不是样式。设置 iframe 大小的样式没有效果:

    $(this).width(newWidth);
    $(this).height(newHeight);
    
  3. 长宽比的计算是错误的(需要比较比率以查看它们重叠的方式)。如果没有这个,则无法满足所有重叠情况。

    var aspect = width/height;
    var parentAspect = parentWidth/parentHeight;
    if (aspect > parentAspect)
    {
        newWidth  = parentWidth;
        newHeight = newWidth / aspect;
    }
    else
    {
        newHeight = parentHeight;
        newWidth  = newHeight * aspect;
    }
    

我还稍微清理了代码以加快元素访问速度。每次调用 jQuery(this) 都会花费周期。

JSFiddle 在这里:http://jsfiddle.net/TrueBlueAussie/ZJDkF/8/

更新:

jsfiddle 现在有 4 种不同重叠场景的示例,每种场景都保留了 iframe 的比例。我还添加了您提到的窗口调整大小,并用它动态调整第一个 div 大小以进行演示。

关于jquery - 使用 jQuery 按比例调整 iframe 大小以适合 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838963/

相关文章:

javascript - 使用 Javascript 从字符串中删除数字

jquery - 在 Jquery 选择器中附加变量

javascript - For循环不显示html中的任何数据

Android ImageView centerCrop 不工作。倾斜而不是缩放

ios - 带有 Retina-Tiles 的 MKTileOverlay

javascript - 更改 Image() 对象尺寸(宽度和高度)

jquery - src 为空时无法设置 IMG 宽度?

delphi - Firemonkey TFrame 对齐 = 缩放错误?

ios - Swift/iOS - 以给定的宽高比保存图像

python - 如何制作 matplotlib 散点图正方形?