我有两个div,.box-1和.box-2。
我想将两者的高度设置为等于高度较大的那个。
谁能告诉我为什么这段代码不能工作?
var $box1Height = $('.box-1').height();
var $box2Height = $('.box-2').height();
if ($box2Height > $box1Height) {
($box1Height).height($box2Height)
} else {
($box2Height).height($box1Height)
}发布于 2018-09-01 03:10:04
要更新的元素是$(".box-1")和$(".box-2")。您没有更新它们,而是获取了它们的高度值,并尝试更新它们的高度值(类似于:$(".box-1").height().height(new_value);,它显然不存在。比较是好的,但更新不是针对正确的元素。
您可以只获取元素$('.box-1')并使用它,而不是使用$('.box-1').height();。
如下所示:
var box1 = $('.box-1');
var box2 = $('.box-2');现在我们有了元素本身,让我们来处理它的属性。要获取元素的高度,请使用:
box1.height();要为此height属性设置新值,请使用:
box1.height(new_value);把所有这些放在一起:
var box1 = $('.box-1');
var box2 = $('.box-2');
if (box1.height() > box2.height()) {
box1.height(box2.height())
} else {
box2.height(box1.height())
}发布于 2018-09-01 03:14:40
您可以通过使用Math.max()获得两者中最大的高度,从而消除了对if语句的需要。然后将两个框的高度都设置为.max()的结果
var maxHeight = Math.max(box1.height(), box2.height())
box1.height(maxHeight)
box2.height(maxHeight)下面是一个工作示例
$(function() {
// cache the box selectors
var box1 = $('.box1')
var box2 = $('.box2')
// determine which box is taller
var maxHeight = Math.max(box1.height(), box2.height())
// apply the tallest height to both
box1.height(maxHeight)
box2.height(maxHeight)
}).box1 {
display: inline-block;
height: 100px;
width: 50px;
background: cornflowerblue;
}
.box2 {
display: inline-block;
height: 50px;
width: 50px;
background: rebeccapurple;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box1">box1</div>
<div class="box2">box2</div>
https://stackoverflow.com/questions/52121406
复制相似问题