用js实现图片的等比缩放还是很方便的,重点在于获取图片的width与height数值,才好进行下一步操作。
这里分享一段js动态计算图片宽度与高度的代码,如下:
// 图片 width 和 height 自动计算的函数
function DrawImage(ImgD, FitWidth, FitHeight) {
var image = new Image();
image.src = ImgD.src;
if (image.width > 0 && image.height > 0) {
if (image.width / image.height >= FitWidth / FitHeight) {
if (image.width > FitWidth) {
ImgD.width = FitWidth;
ImgD.height = (image.height * FitWidth) / image.width;
} else {
ImgD.width = image.width;
ImgD.height = image.height;
}
} else {
if (image.height > FitHeight) {
ImgD.height = FitHeight;
ImgD.width = (image.width * FitHeight) / image.height;
} else {
ImgD.width = image.width;
ImgD.height = image.height;
}
}
}
}
// 开始执行
jquery(window).load(function () {
jQuery("li.item img").each(function () {
DrawImage(this, 800, 600);
});
});