0

我正在尝试根据browzersize动态调整div高度,并基于此脚本(在 此处找到):

$(document).ready(function() {
    setHeight('.col');
});

var maxHeight = 0;
function setHeight(column) {
    //Get all the element with class = col
    column = $(column);
    //Loop all the column
    column.each(function() {       
        //Store the highest value
        if($(this).height() > maxHeight) {
            maxHeight = $(this).height();;
        }
    });
    //Set the height
    column.height(maxHeight);
}

脚本效果很好,我只需要在调整浏览器窗口大小以实现响应目的时也运行它。

做这样的事情是有意义的:

$(window).resize(function() {
setHeight('.col');
});

然后还以某种方式重置“maxHeight”......

没有 bueno - 有什么想法吗?

4

2 回答 2

3

工作 jsFiddle 演示

对于该setHeight函数第一次运行,height元素的初始化。第二次,总是返回相同的高度。您必须height在循环之前从它们中删除:

column.css('height', 'auto');

而且,您还var maxHeight = 0;必须在您的函数中:

$(document).ready(function() {
    setHeight('.col');
});


function setHeight(column) {
    var maxHeight = 0;
    //Get all the element with class = col
    column = $(column);
    column.css('height', 'auto');
    //Loop all the column
    column.each(function() {       
        //Store the highest value
        if($(this).height() > maxHeight) {
            maxHeight = $(this).height();
        }
    });
    //Set the height
    column.height(maxHeight);
}


$(window).resize(function() {
    setHeight('.col');
});
于 2013-05-31T15:21:28.990 回答
1

编辑:给你。这个对我有用 :)

$(document).ready(function() {
   setHeight('.col');

   /*if this is not placed before it is to be called, 
     the browser won't recognize it, 
     which is why i preferably register these 
     event functions in ready()*/
   window.onresize=function(){setHeight('.col');}; 
});

function setHeight(column) {
   var maxHeight = 0;   
   //Get all the element with class = col
   column = $(column);
   //Loop all the column
   column.each(function() {       
   //Store the highest value
     if($(this).height() > maxHeight) {
      maxHeight = $(this).height() ;
     }
  });
   //Set the height
   column.height(maxHeight);
   console.log(column +" " + maxHeight);
}

误读了 q:将 maxHeight 变量设为函数的局部变量。每当您退出该功能时,它的值就会被重置。

于 2013-05-30T13:33:30.610 回答