2014-01-16 88 views
0

這裏是我的問題。我想保留一張照片的長寬比,並將其放入一個風景格。問題是我想在高度上合適圖片並在寬度上裁剪。這裏是我用來適合圖片的腳本,但它適合寬度而不是高度。根據身高保持縱橫比

<script> 
$(document).ready(function() { 
    $('.story-small img').each(function() { 
     var maxWidth = 550; // Max width for the image 
     var maxHeight = 413; // 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 > maxWidth){ 
      ratio = maxWidth/width; // get ratio for scaling image 
      $(this).css("width", maxWidth); // Set new width 
      $(this).css("height", height * ratio); // Scale height based on ratio 
      height = height * ratio; // Reset height to match scaled image 
      width = width * ratio; // Reset width to match scaled image 
     } 

     // Check if current height is larger than max 
     if(height > maxHeight){ 
      ratio = maxHeight/height; // get ratio for scaling image 
      $(this).css("height", maxHeight); // Set new height 
      $(this).css("width", width * ratio); // Scale width based on ratio 
      width = width * ratio; // Reset width to match scaled image 
     } 
    }); 
}); 
</script> 

這裏有一個例子:Link

所以practicly第二張圖是美好的事業它適合於高度,這就是我想achiev景觀圖片,適合在高剪切寬度。 Thnx提前。

+0

你也許可以做到這一點只用CSS,沒有劇本,但我不正是理解你正在努力達到什麼。你想保持圖像的高度,並裁剪其寬度以適應div寬度?你能展示一個效果的截圖例子嗎? – CodeToad

回答

0

試試這個:

fiddle

CSS:

img{ 
max-width: 550px; 
max-height:440px; 
} 

HTML:

<img src="http://websoftit.ro/dragdrop/emma-watson-wallpaper-1920x1200.jpg">