You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确保每次刷新浏览器时都能正确计算父div高度?

问题求助:确保jQuery在子元素加载完成后计算父元素高度

我有个设置为position:relative的父div,还有个设置为position:absolute的子div。我希望在页面加载时计算父div的高度,目前用下面这段jQuery代码实现了首次加载计算,也能在用户调整浏览器窗口大小的时候重新计算高度,这部分是符合我需求的。

但现在遇到个问题:当用户多次刷新页面时,jQuery有时候没法在首次加载时计算出正确的高度。我该怎么确保始终等待子div完全加载完成后再去获取它的高度呢?

我当前使用的jQuery代码:

$(function() {
    //Calculate the height on first load
    $('.OV2-img, .col1').height($('.col1-img').outerHeight());
    //Calculate the height on browser resize
    $(window).resize(function() {
        $('.OV2-img, .col1').height($('.col1-img').outerHeight());
    });
});

说实话我不太擅长JS,希望我表述清楚了,提前感谢大家的帮助!


已找到解决方案

感谢Mosh Feu的优秀建议,我现在把代码修改成了这样:

$(function () {
    //Calculate the height on first load
    $(window).load(function () {
        $('.OV2-img, .col1').height($('.col1-img').outerHeight());
    });
    //Calculate the height on browser resize
    $(window).resize(function () {
        $('.OV2-img, .col1').height($('.col1-img').outerHeight());
    });
});

感谢各位的热心帮助!这个方案能在任意屏幕尺寸下保留图片与颜色框之间的间距~

内容的提问来源于stack exchange,提问作者StrangeLove

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:24:54