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

时间:2014-11-27 20:51:33

标签: javascript html css

如果没有jQuery和纯JavaScript,我该如何做到以下几点:

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

下面的jQuery方法正在运行,但我想用JavaScript做到这一点。

请参阅小提琴here.

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" );
    }
  });
});

4 个答案:

答案 0 :(得分:1)

所以有点令人困惑,但你是说jquery版本正在运行,但你想在普通的javascript中使用它吗?

如果是这样的话:

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

是一个等同的陈述。

答案 1 :(得分:1)

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 - 将Height设置为父节点,如果父节点不是数字

演示:http://jsfiddle.net/6tjn7675/4/

答案 2 :(得分:0)

尝试这样的事情:

<强> HTML

<div class="image-container">

/* image goes here */

</div>

<强>的jQuery

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

答案 3 :(得分:0)

从我记忆中来看:

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

修改 刚看到Dave Walker的回答。 naturalWidth和naturalHeight将为您提供图像的原始高度和宽度。要获得计算/显示的高度和宽度,必须使用offsetHeight和offsetWidth。