如何使用jQuery将多个DIV保持相同的高度?

前端之家收集整理的这篇文章主要介绍了如何使用jQuery将多个DIV保持相同的高度?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一些带有不同文本内容的DIV标签.

HTML

  1. Boxes">
  2. Boxone">
  3. Boxtwo">
  4. Boxthree">
  5. Boxfour">

它们采用2×2布局,宽度适中:

CSS:

  1. div#Boxes {
  2. width: 100%;
  3. }
  4. div#Boxes div {
  5. width: 49.9%;
  6. float: left;
  7. }

我希望他们都有相同的高度.

所以,我循环遍历它们并找到最高的高度.然后我再次循环并将它们全部设置到那个高度.

jQuery的:

  1. $(function() {
  2. var maxHeight = 0;
  3. $('div#Boxes div').each(function(){
  4. if (maxHeight < $(this).height()) {maxHeight = $(this).height()}
  5. });
  6. $('div#Boxes div').each(function(){
  7. $(this).height(maxHeight);
  8. });
  9. });

如果div的高度不需要再次更改,这很有效.

但是,如果我调整浏览器窗口大小,则会失败:

>如果我(a)使浏览器更宽,那么(b)我的
DIV变宽,然后(c)他们的文本
内容包裹次数减少,然后(d)
我的DIV太高了.
>如果我(b)使浏览器更窄,
然后(b)我的DIV变得更窄,然后(c)
他们的文字内容包含更多,并且
然后(d)我的DIV太短了.

我如何(1)自动将DIV大小调整到正常的内容高度,还(2)保持多个DIV的高度相同?

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

  1. function sortNumber(a,b) {
  2. return a - b;
  3. }
  4. function maxHeight() {
  5. var heights = new Array();
  6. $('div#Boxes div').each(function(){
  7. $(this).css('height','auto');
  8. heights.push($(this).height());
  9. heights = heights.sort(sortNumber).reverse();
  10. $(this).css('height',heights[0]);
  11. });
  12. }
  13. $(document).ready(function() {
  14. maxHeight();
  15. })
  16. $(window).resize(maxHeight);

我注意到的一件事是,IE真的有50%宽浮动div的四舍五入的问题…如果我将它们改为49%,那么渲染会好得多.

这个jQuery有效……

  1. // global variables
  2. doAdjust = true;
  3. prevIoUsWidth = 0;
  4. // raise doAdjust flag every time the window width changes
  5. $(window).resize(function() {
  6. var currentWidth = $(window).width();
  7. if (prevIoUsWidth != currentWidth) {
  8. doAdjust = true;
  9. }
  10. prevIoUsWidth = currentWidth;
  11. })
  12. // every half second
  13. $(function() {
  14. setInterval('maybeAdjust()',500);
  15. });
  16. // check the doAdjust flag
  17. function maybeAdjust() {
  18. if (doAdjust) {
  19. adjustBoxHeights();
  20. doAdjust = false;
  21. }
  22. }
  23. // loop through the DIVs and find the height of the tallest one
  24. // then loop again and set them all to that height
  25. function adjustBoxHeights() {
  26. var maxHeight = 0;
  27. $('div#Boxes div').each(function(){
  28. $(this).height('auto');
  29. if (maxHeight < $(this).height()) {maxHeight = $(this).height()}
  30. });
  31. $('div#Boxes div').each(function(){
  32. $(this).height(maxHeight);
  33. });
  34. }

猜你在找的HTML相关文章