gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:55:22 24 4
gpt4 key购买 nike

我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com