html三个div相同高度,如何使用jquery保持多个div的高度相同?

这段代码展示了如何使用jQuery调整div#boxesdiv的高度,使其根据内容自动排序并保持一致的最大高度。同时,注意到对于50%宽度的浮动元素存在舍入问题,改用49%可以改善效果。代码中还包括窗口大小变化时的响应式调整,并通过doAdjust标志控制调整频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

更新

…在尝试并找到另一种显然可行的方法后,完全重写此答案:

function sortNumber(a,b) {

return a - b;

}

function maxHeight() {

var heights = new Array();

$('div#boxes div').each(function(){

$(this).css('height', 'auto');

heights.push($(this).height());

heights = heights.sort(sortNumber).reverse();

$(this).css('height', heights[0]);

});

}

$(document).ready(function() {

maxHeight();

})

$(window).resize(maxHeight);

我注意到的一件事是,50%宽的浮动式沙发床确实存在舍入问题。如果我把它们改成49%,效果会好得多。

这个jquery工作…

// global variables

doAdjust = true;

previousWidth = 0;

// raise doAdjust flag every time the window width changes

$(window).resize(function() {

var currentWidth = $(window).width();

if (previousWidth != currentWidth) {

doAdjust = true;

}

previousWidth = currentWidth;

})

// every half second

$(function() {

setInterval('maybeAdjust()', 500);

});

// check the doAdjust flag

function maybeAdjust() {

if (doAdjust) {

adjustBoxHeights();

doAdjust = false;

}

}

// loop through the DIVs and find the height of the tallest one

// then loop again and set them all to that height

function adjustBoxHeights() {

var maxHeight = 0;

$('div#boxes div').each(function(){

$(this).height('auto');

if (maxHeight < $(this).height()) {maxHeight = $(this).height()}

});

$('div#boxes div').each(function(){

$(this).height(maxHeight);

});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值