下面的代码非常适合按高度按纵横比调整图像大小,我还可以按宽度创建单独的函数。但我并不总是确定图像是否需要按高度或宽度缩小。
例如,如果图像需要调整大小的空间是 100 宽和 100 高,而图像是 150 x 90,那么它需要缩小的宽度。如果图像是 80 x 160,则需要缩小高度。
所以我要问的是如何修改下面的代码,以便按纵横比缩小图像以适应宽度和高度的参数?谢谢。
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
if (this.aspectRatio == undefined)
this.aspectRatio = parseInt($(this).width() / $(this).height());
$(this).height(newHeight);
$(this).width(newHeight * this.aspectRatio);
}
我再次编辑了代码,因为经过进一步检查,我的更新版本和 Dan 的版本似乎都无法正常工作。纵横比丢失了,所以这里还有另一个。我已经在一张图片上试过了,到目前为止一切都很好。这里是,
jQuery.fn.resizeMaintainRatio = function(newHeight, newWidth){
widthRatio = parseInt($(this).width() / newWidth);
heightRatio = parseInt($(this).height() / newHeight);
if(heightRatio > widthRatio)
{
this.aspectRatio = parseInt($(this).css("width") / $(this).css("height"));
$(this).css("height", newHeight);
$(this).css("width", newHeight * this.aspectRatio);
}
else{
this.aspectRatio = parseInt($(this).css("height") / $(this).css("width"));
$(this).css("width", newWidth);
$(this).css("height", newWidth * this.aspectRatio);
}
}
再次注意:进一步使用上面的代码后,工作非常奇怪,试试这个 - http://plugins.jquery.com/project/kepresize