我在这里搜索了这个问题并找到了几个例子,我特别尝试了一个,但它根本没有像我想要的那样工作。
我已将容器的高度设置为 600 像素,但它甚至还差得远。我确定这是因为我的图像宽度只有 33%,但是有没有办法让这些宽度变高,或者我是否只能将高度限制在这么高?
我不明白为什么最右边的图像甚至没有到达容器的顶部。我至少希望它是那样的。
无论如何都可以调整这些图像的高度,还是会完全不成比例?
$(window).load(function(){
$('.home-img-block').find('img').each(function(){
var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
$(this).addClass(imgClass);
})
})
#home-img-blocks {
width: 100%;
height: 600px;
}
/*#home-img-blocks-container {
border: 1px solid black;
}*/
.home-img-block {
width: 33%;
height: 100%;
border: 1px solid black;
display: inline-block;
}
.home-img-block img.wide {
max-width: 100%;
max-height: 100%;
max-width: 100%;
height: auto;
}
.home-img-block img.tall {
max-width: 100%;
max-height: 100%;
max-width: 100%;
width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="home-img-blocks">
<div class="home-img-block"><img src="http://optimumwebdesigns.com/images/test1.jpg"></div><div class="home-img-block"><img src="http://optimumwebdesigns.com/images/test2.jpg">
</div><div class="home-img-block"><img src="http://optimumwebdesigns.com/images/test3.jpg"></div>
</div>
最佳答案
按照以下方式,您可以覆盖容器的整个高度。从图像中删除 max-width
并将 vertical-align:top
和 overflow: hidden;
给容器。
但不是这样,它会剪切您的图像,因为它不会保持纵横比,因为高度太高而宽度太小。
$(window).load(function(){
$('.home-img-block').find('img').each(function(){
var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
$(this).addClass(imgClass);
})
})
#home-img-blocks {
width: 100%;
height: 600px;
}
/*#home-img-blocks-container {
border: 1px solid black;
}*/
.home-img-block {
width: 33%;
height: 100%;
border: 1px solid black;
display: inline-block;
overflow: hidden;
vertical-align: top;
}
.home-img-block img.wide {
max-height: 100%;
}
.home-img-block img.tall {
max-width: 100%;
max-height: 100%;
max-width: 100%;
width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="home-img-blocks">
<div class="home-img-block"><img src="http://optimumwebdesigns.com/images/test1.jpg"></div><div class="home-img-block"><img src="http://optimumwebdesigns.com/images/test2.jpg">
</div><div class="home-img-block"><img src="http://optimumwebdesigns.com/images/test3.jpg"></div>
</div>
关于javascript - 调整图像大小以完美适合容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34915282/