Dre*_*ker 4 jquery scale aspect-ratio
我在div中有一个视频的iframe,如下所示:
<div class="media">
<iframe>
</div>
Run Code Online (Sandbox Code Playgroud)
我在窗口调整大小时动态设置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'
});
});
};
Run Code Online (Sandbox Code Playgroud)
基本上,我希望复制"background-size:contains"对CSS中的图像进行的大小调整,但是对于DIV中的iframe.
谢谢您的帮助!
注意到三个问题:
您的示例中有错误(尾随引用):
:newWidth'
您需要设置iframe实际高度和宽度属性,而不是样式.样式化iframe大小无效:
$(this).width(newWidth);
$(this).height(newHeight);
Run Code Online (Sandbox Code Playgroud)宽高比的计算是错误的(需要比较比率以查看它们重叠的方式).如果没有这一点,并非所有重叠案例都能满足.
var aspect = width/height;
var parentAspect = parentWidth/parentHeight;
if (aspect > parentAspect)
{
newWidth = parentWidth;
newHeight = newWidth / aspect;
}
else
{
newHeight = parentHeight;
newWidth = newHeight * aspect;
}
Run Code Online (Sandbox Code Playgroud)我还清理了一些代码以加快元素访问速度.每次调用jQuery(this)都需要花费很多时间.
jsfiddle现在有4个不同重叠场景的例子,每个场景都保留了iframe的比例.我还添加了你提到的窗口调整大小,并使第一个div动态调整大小以进行演示.
| 归档时间: |
|
| 查看次数: |
7746 次 |
| 最近记录: |