2015-05-20 60 views
1

div标签有图像。我必须更改div的宽度和高度。如果我更改标签的宽度和高度,图像的宽度和高度会自动改变为原始图像的比例。但是,使用jQuery或Javascript,图像大小不应超过原始大小。自动更改图像大小的原始比例,同时更改该图像的大小父元素

<div> 
    <img src="logo.jpg"/> 
</div> 
+1

你尝试过什么? – ketan

+0

@Gowtham V你可以设置'img {width:100%}'并且检查 – vas

+1

@vas如果图像的高度大于'width',这不起作用 – Tushar

回答

0

你可能想打电话window.load此功能:

$('img:visible').each(function() { 
    // For visible images only 
    var imageWidth, 
     imageHeight, 
     aspectRatio; 

    var parentWidth = $(this).parent().width(), 
     parentHeight = $(this).parent().height(); 

    if (this.naturalWidth > parentWidth || this.naturalHeight > parentHeight) { 
     aspectRatio = this.naturalWidth/this.naturalHeight; // Actual image width and height 

     if (this.naturalWidth > this.naturalHeight) { 
      imageWidth = parentWidth - 50; // Leave margin 
      imageHeight = imageWidth/aspectRatio; 
     } else { 
      imageHeight = parentHeight - 10; // Leave some space 
      imageWidth = imageHeight * aspectRatio; 
     } 

     $(this).css({ 
      'width': imageWidth, 
      'height': imageHeight 
     }); 
    } 
}); 

演示:https://jsfiddle.net/tusharj/onytgawp/

+0

非常感谢你 – Kallis

0

使用max-width和max-height css属性。

+0

非常感谢你 – Kallis