【发布时间】:2020-01-13 08:21:53
【问题描述】:
如何计算子 DIV 的高度和宽度。
我想计算每个子 DIV 的高度和宽度,然后比较它的宽度和高度。如果宽度大于高度,则添加 class1 或高度大于宽度,然后添加 class2。并且宽度等于高度然后添加 class3
$(window).load(function() {
$('.grid').children().each(function(item) {
var divHeight = 0;
var divWidth = 0;
divHeight = $('.grid-item').height();
divWidth = $('.grid-item').width();
console.log(divWidth);
console.log(divHeight);
//check if child div's width is greater then height then add some class
if ($(this).width() > $(this).height()) {
if ($(this).hasClass('class1')) {
$(this).removeClass('class1');
} else {
$(this).addClass('class1');
}
}
});
});
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
/* ---- grid ---- */
h1 {
text-align: center
}
.grid {
background: #DDD;
max-width: 1200px;
margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Isotope - masonry layout mode</h1>
<div class="grid">
<div class="grid-item">
<img src="https://via.placeholder.com/300/09f/fff.png" alt="">
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/728x90.png" alt="">
</div>
<div class="grid-item">
<img src="https://via.placeholder.com/500x100.png" alt="">
</div>
</div>
【问题讨论】:
-
您有控制台错误
-
@mplungjan 是的,感谢编辑!
标签: javascript jquery html css jquery-masonry