How to resize images proportionally / keeping the aspect ratio?

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

    Without additional temp-vars or brackets.

        var width= $(this).width(), height= $(this).height()
          , maxWidth=100, maxHeight= 100;
    
        if(width > maxWidth){
          height = Math.floor( maxWidth * height / width );
          width = maxWidth
          }
        if(height > maxHeight){
          width = Math.floor( maxHeight * width / height );
          height = maxHeight;
          }
    

    Keep in Mind: Search engines don't like it, if width and height attribute does not fit the image, but they don't know JS.

提交回复
热议问题