2012-02-14 111 views
1

我正在嘗試調整圖像大小,但不會將其增加到其原始大小以上 - 我也想將圖像居中放在其容器中。這是做這件事的最好方式,因爲有時候它看起來有點生澀?調整縱橫比的圖像

我已經取出了jquery js鏈接。

<html> 
    <head> 
     <style type="text/css"> 
      .container { 
       width: 100%; 
       height: 100%; 
       background: #444; 
      } 
     </style>     
    </head> 

    <body> 
     <div class="container"> 
      <img src="D:\large.png" /> 
     </div> 
    </body> 

    <script> 
     var $orig_width=0; 
     var $orig_height=0; 
     var width; 
     var height; 
     var $img; 

     $(window).load(function() {    
      $img = $('.container').find('img');  
      $orig_width=$img.width(); 
      $orig_height=$img.height(); 
      resize();   
     }); 

     function resize() { 
      var width=$img.width(); 
      var height=$img.height();  
      var parentWidth = $img.parent().width(); 
      var parentHeight = $img.parent().height(); 

      newWidth = parentWidth; 
      newHeight = newWidth/width*height; 

      if (newHeight>$orig_height) newHeight=$orig_height;  
      if (newWidth>$orig_width) newWidth=$orig_width; 

      margin_top = (parentHeight - newHeight)/2; 
      margin_left = ((parentWidth - newWidth)/2); 

      $img.css({'margin-top' :margin_top + 'px', 
         'margin-left':margin_left + 'px', 
         'height'  :newHeight + 'px', 
         'width'  :newWidth + 'px'}); 
     } 

     $(window).resize(function() {   
      resize();   
     })  

    </script> 

</html> 

回答

0

似乎OK,現在用jQuery版本1.7.2工作

0

我在這樣的情況下max-width:100%;代替width:100%;使用。

1

您只是使用表格作爲容器。因爲你很容易將它與桌子對齊。 將固定的寬度和高度設置爲屬性將爲固定大小的圖像帶來解決方案。