How to resize images proportionally / keeping the aspect ratio?

前端 未结 18 1859
野趣味
野趣味 2020-11-22 13:58

I have images that will be quite big in dimension and I want to shrink them down with jQuery while keeping the proportions constrained, i.e. the same aspect ratio.

C

18条回答
  •  时光取名叫无心
    2020-11-22 14:33

    This should work for images with all possible proportions

    $(document).ready(function() {
        $('.list img').each(function() {
            var maxWidth = 100;
            var maxHeight = 100;
            var width = $(this).width();
            var height = $(this).height();
            var ratioW = maxWidth / width;  // Width ratio
            var ratioH = maxHeight / height;  // Height ratio
    
            // If height ratio is bigger then we need to scale height
            if(ratioH > ratioW){
                $(this).css("width", maxWidth);
                $(this).css("height", height * ratioW);  // Scale height according to width ratio
            }
            else{ // otherwise we scale width
                $(this).css("height", maxHeight);
                $(this).css("width", height * ratioH);  // according to height ratio
            }
        });
    });
    

提交回复
热议问题