Eri*_*ric 19
这是一个有用的功能,可以做你想要的:
jQuery.fn.fitToParent = function()
{
this.each(function()
{
var width = $(this).width();
var height = $(this).height();
var parentWidth = $(this).parent().width();
var parentHeight = $(this).parent().height();
if(width/parentWidth < height/parentHeight) {
newWidth = parentWidth;
newHeight = newWidth/width*height;
}
else {
newHeight = parentHeight;
newWidth = newHeight/height*width;
}
var margin_top = (parentHeight - newHeight) / 2;
var margin_left = (parentWidth - newWidth ) / 2;
$(this).css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :newHeight + 'px',
'width' :newWidth + 'px'});
});
};
Run Code Online (Sandbox Code Playgroud)
基本上,它抓取一个元素,将其置于父级中心,然后将其拉伸以使父级的背景都不可见,同时保持宽高比.
然后,这可能不是你想要做的.
Pau*_*aul 13
你可以手动计算,
即:
function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}
Run Code Online (Sandbox Code Playgroud)
确保使用图像的ORIGINAL值,否则它会随着时间的推移而降级.
编辑:示例jQuery版本(未测试)
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
var aspectRatio = $(this).data('aspectRatio');
if (aspectRatio == undefined) {
aspectRatio = $(this).width() / $(this).height();
$(this).data('aspectRatio', aspectRatio);
}
$(this).height(newHeight);
$(this).width(parseInt(newHeight * aspectRatio));
}
Run Code Online (Sandbox Code Playgroud)
$("#some_image").resizable({ aspectRatio:true, maxHeight:300 });
Run Code Online (Sandbox Code Playgroud)
aspectRatio:true - >保持原始宽高比
| 归档时间: |
|
| 查看次数: |
55943 次 |
| 最近记录: |