如果没有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" );
}
});
});
答案 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';
}
});
}
答案 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
获取所有图像节点。naturalHeight
和naturalWidth
属性可以获得图像的计算高度和宽度。parentNode
属性将为您提供父级。应用所需的样式,你应该完成。修改强> 刚看到Dave Walker的回答。 naturalWidth和naturalHeight将为您提供图像的原始高度和宽度。要获得计算/显示的高度和宽度,必须使用offsetHeight和offsetWidth。