基于 window 使用 jQuery 调整大小和方向的动态像素值

Dynamic pixel value based on window re-size and orientation using jQuery

我目前正在使用以下方法计算 <div> 的高度:

var new_height = $('.div-1').outerHeight(true);

.div-1没有固定的高度,高度是根据内容的多少来计算的。

我使用此值将内联样式添加到另一个元素,如下所示:

$('.div-2').css('top',new_height);

所以如果计算出的高度是 590px,我得到:

<div class="div-2" style="top: 590px;">

我想进一步扩展它,以便 new_height 值是动态的。因此,如果设备方向发生变化或浏览器宽度发生变化,我会即时获得一个新值。我认为我的解决方案并不遥远,其他类似问题似乎没有给我我需要的答案。如果可能,我想避免刷新页面。

您可以使用以下代码在每次调整页面大小时重新计算上边距:

function setTopMargin() {
    //figure out and set your margin here
}

var resizeTimer = null;
$(window).resize(function () { 
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() { setTopMargin(); }, 75);
});

计时器可确保在用户调整 window 大小时不会过于频繁地调用函数。