How to resize images proportionally / keeping the aspect ratio?

前端 未结 18 1670
野趣味
野趣味 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:29

    $('#productThumb img').each(function() {
        var maxWidth = 140; // Max width for the image
        var maxHeight = 140;    // Max height for the image
        var ratio = 0;  // Used for aspect ratio
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height
        // Check if the current width is larger than the max
        if(width > height){
            height = ( height / width ) * maxHeight;
    
        } else if(height > width){
            maxWidth = (width/height)* maxWidth;
        }
        $(this).css("width", maxWidth); // Set new width
        $(this).css("height", maxHeight);  // Scale height based on ratio
    });
    

提交回复
热议问题