我正在尝试确定容器中图像的高度,如果任何图像的高度小于 300 像素,那么我希望将其容器高度设置为自动。
这是我的代码:
<style>
.container {
width: 500px;
height: 500px;
}
</style>
<script>
var img = document.getElementsByTagName("img");
if (img.height < 300) {
var x = document.getElementsByClassName('container');
x.style.height="auto";
}
</script>
<div class="container">
<img height="500" width="500" src="/some_img.jpg"/>
</div>
<div class="container">
<img height="500" width="500" src="/some_img.jpg"/>
</div>
<div class="container">
<img height="500" width="500" src="/some_img.jpg"/>
</div>
<div class="container">
<img height="250" width="250" src="/some_img.jpg"/> // This image height is less than 300 pixels.
</div>
<div class="container">
<img height="500" width="500" src="/some_img.jpg"/>
</div>
如有任何帮助,我们将不胜感激。
最佳答案
首先获取所有图片标签,然后遍历它们,如果它们的高度小于 500,则获取其父元素并将其高度设置为 'auto' here是一个工作示例
var img = document.getElementsByTagName("img");
console.log(img)
for (index in img){
if (img[index].height < 300) {
img[index].parentNode.style.height="auto";
}
}
关于javascript - 获取图像高度并将图像容器高度更改为自动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26723856/