2013-05-30 105 views
0

我试图动态调整基于browzersize DIV的高度,并在此基础上脚本高度(发现here):调整大小的div使用jQuery

$(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”莫名其妙......

没有布埃诺 - 任何想法?

+0

通过“响应的目的”当用户停止调整你的意思窗户? –

+1

你需要把'var maxHeight = 0;'函数 – Pete

+0

放在我做的皮特里面。在这里发布的代码:http://jsfiddle.net/f99mD/1/与“Imbecile”的建议 – user2436715

回答

2

Working jsFiddle Demo

对于thie首次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'); 
}); 
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变量局部于该函数。它的价值将被重置,每当你退出该功能。

+0

试过了,仍然没有工作 – user2436715

+0

怎么样:window.onresize = function(){setHeight('。col'); };如果你被允许使用JS以及 – imbecile

+0

stil否...发布我的代码在这里:http://jsfiddle.net/f99mD/也许我不是做对了... – user2436715