Jquery implements a scaled image example

  • 2020-03-30 03:27:49
  • OfStack


  <html> 
    <title></title> 
    <head></head> 
    <style> 
      .thumbnail{overflow:hidden;width:400px;height:240px;} 
    </style> 
    <script src="http://code.jquery.com/jquery-1.4.1.min.js"></script> 
    <script language="javascript"> 
      $(function(){ 
         
          $('#content div.thumbnail img').each(function(){ 
            var x = 400; //Fill in the target image width
            var y = 240; //Fill in the target image height
            var w=$(this).width(), h=$(this).height();//Gets the width and height of the image
            if (w > x) { //When the image width is larger than the target width
              var w_original=w, h_original=h; 
              h = h * (x / w); //Calculate the height proportional to the target width
              w = x; //The width is equal to the predetermined width
              if (h < y) { //If the scaled down height is less than the predetermined height
                w = w_original * (y / h_original); //Recalculate the width by the target height
                h = y; //The height is equal to the predetermined height
              } 
            } 
            $(this).attr({width:w,height:h}); 
          }); 
      }); 
    </script> 
    <body> 
    <div id="content"> 
      <div id="thumbnail" class="thumbnail" > 
        <img id="web" src="./midle.png"/> 
      </div> 
     </div> 
    </body> 
  </html>

Related articles: