如何获取图像的高度并将其父高度设置为自动

How to get an image's height and set its parent height to auto?

本文关键字:高度 设置 获取 图像 何获取      更新时间:2023-09-26

如何在没有jQuery和纯JavaScript的情况下执行以下操作:

我要做的是在图形元素中获取图像的高度,如果图像的高度小于 200 像素,则我希望将其容器(父级)的高度设置为自动。

下面的jQuery方法可以工作,但我想用JavaScript来做到这一点。

在这里看到小提琴。

.HTML

<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>
<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>
<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>
<figure>
<img class="imgH" height="250" width="250" src="/some_img.jpg"/> // This image height is less than 300 pixels.
</figure>
<figure>
<img class="imgH" height="500" width="500" src="/some_img.jpg"/>
</figure>

.CSS

figure {
 width: 500px;
 height: 500px;
}

JavaScript (jQuery)

$(document).ready(function(){
  $(".imgH").each(function(){
    if( $(this).height() < 200 ) {
        $(this).parent().height( "auto" );
    }
  });
});
window.onload = function () {
    [].forEach.call( document.querySelectorAll('.imgH'), function(node, i) {
        if (node.clientHeight < 200) {
            node.parentNode.style.height = 'auto';    
        }
    });
}
  • document.querySelectorAll('.imgH') - 返回具有类的节点imgH,
  • node.clientHeight - 获取图像高度
  • node.parentNode.style.height - 将高度设置为父节点,在这种情况下,父节点不是图形

德莫: http://jsfiddle.net/6tjn7675/4/

有点令人困惑,但你是说jquery版本可以工作,但你想要它在普通的javascript中吗?

如果是这样,则如下所示:

    if( this.offsetHeight< 200 ) {
        var container = this.parentNode;
        container.style.height = "auto";
    }

是等效语句。

尝试这样的事情:

.HTML

<div class="image-container">
/* image goes here */
</div>

jQuery

$('.image-container').each(function() {
        if ($(this).find('img').length < 300 ) {
            $(this).css({'height' 'auto'});
        }
        });

据我所知:

  • 您可以使用document.querySelector来获取所有映像节点。
  • naturalHeightnaturalWidth属性将为您提供计算出的图像的高度和宽度。
  • 图像节点parentNode属性将获取父节点。应用所需的样式,您应该完成。

编辑:刚刚看到戴夫沃克的回答。naturalWidth 和 naturalHeight 将为您提供图像的原始高度和宽度。要获取计算/显示的高度和宽度,您必须使用 offsetHeight 和 offsetWidth。