我正在尝试根据browzersize动态调整div高度,并基于此脚本(找到here):
$(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 - 任何想法?
答案 0 :(得分:2)
首次运行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 :(得分: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变量设为函数的局部变量。无论何时退出该函数,它的值都将被重置。