div标签有图像。我必须更改div的宽度和高度。如果我更改标签的宽度和高度,图像的宽度和高度会自动改变为原始图像的比例。但是,使用jQuery或Javascript,图像大小不应超过原始大小。自动更改图像大小的原始比例,同时更改该图像的大小父元素
<div>
<img src="logo.jpg"/>
</div>
div标签有图像。我必须更改div的宽度和高度。如果我更改标签的宽度和高度,图像的宽度和高度会自动改变为原始图像的比例。但是,使用jQuery或Javascript,图像大小不应超过原始大小。自动更改图像大小的原始比例,同时更改该图像的大小父元素
<div>
<img src="logo.jpg"/>
</div>
你可能想打电话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
});
}
});
非常感谢你 – Kallis
Try this,
img{
max-width:100%;
max-height:100%;
}
你尝试过什么? – ketan
@Gowtham V你可以设置'img {width:100%}'并且检查 – vas
@vas如果图像的高度大于'width',这不起作用 – Tushar