Javascript 自动更改原始比例的图像大小,同时更改该图像父元素的大小
div标记有一个图像。我必须更改div的宽度和高度。如果我更改标记的宽度和高度,该图像的宽度和高度将按照图像的原始比例自动更改。但是,使用jQuery或Javascript,图像大小不应超过原始大小Javascript 自动更改原始比例的图像大小,同时更改该图像父元素的大小,javascript,jquery,html,css,image,Javascript,Jquery,Html,Css,Image,div标记有一个图像。我必须更改div的宽度和高度。如果我更改标记的宽度和高度,该图像的宽度和高度将按照图像的原始比例自动更改。但是,使用jQuery或Javascript,图像大小不应超过原始大小 <div> <img src="logo.jpg"/> </div> 使用最大宽度和最大高度css属性。您可能希望在窗口上调用此函数。加载: $('img:visible').each(function() { // For visible i
<div>
<img src="logo.jpg"/>
</div>
使用最大宽度和最大高度css属性。您可能希望在窗口上调用此函数。加载
:
$('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
});
}
});
演示:你试过什么吗?@Gowtham V你能设置
img{width:100%}
和check@vas如果图像的高度
大于宽度
@Gowtham,这不起作用,到目前为止有任何努力吗?在你的css中使用此标志{最大宽度:100%;高度:自动;显示:bolck;}
Try this,
img{
max-width:100%;
max-height:100%;
}