我有一个函数,我用它来使一堆同级 div
具有相同的高度。当 DOM 准备就绪时,我定义它、调用它,然后将它设置为在 window
被 resiz
时调用。
jQuery(function($){
function rescaleStuff ( )
{
$('.children-have-equal-height').each(function(){
var children = $(this).children();
var numChildren = children.length;
if (numChildren > 1)
{
var firstChild = children.first();
var maxHeight = firstChild.height();
firstChild.siblings().each(function() {
var thisHeight = $(this).height();
if (thisHeight > maxHeight)
maxHeight = thisHeight;
});
children.height(maxHeight);
}
});
}
rescaleStuff();
$(window).resize(function()
{
rescaleStuff();
});
});
rescaleStuff
函数在通过调整 window
大小时调用时工作得非常好,但是当页面负载。出于某种原因,它计算的高度小于实际高度。这是为什么?
此外,是否可以使我的程序更加紧凑、优雅、可读、高效、智能和可维护?我不这么认为。 ;)
最佳答案
使用:
$( window ).load(function() {
....
});
如果您必须计算宽度/高度、位置... ready() 方法是不够的。您必须等到整个内容(带有图像)加载完毕,因为内容会影响高度和宽度。
关于javascript - 为什么这个函数在页面加载时没有预期的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32107443/