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

JavaScript渲染DOM元素后读取其高度的方法(不使用setTimeout)

解决方案:DOM渲染完成后读取元素高度(无需setTimeout)

方法一:使用requestAnimationFrame

requestAnimationFrame的回调会在浏览器下一次重绘前执行,能确保所有DOM修改已被处理、元素布局计算完成,此时读取高度会得到准确值:

wordsArray.forEach((word, index) => {
    $('#adjective').append(`<div style='opacity: ${index === 0 ? 1 : 0};'>${word}</div>`)
})

requestAnimationFrame(() => {
    // 读取第一个div的高度
    const targetHeight = $('#adjective div:first').height();
    console.log('元素高度:', targetHeight);
    
    // 若要读取指定索引的div(比如第2个,索引从0开始):
    // const targetHeight = $('#adjective div').eq(1).height();
});

方法二:直接读取(利用浏览器重排特性)

jQuery的height()方法、原生的offsetHeight或getBoundingClientRect()会强制浏览器立即计算元素布局(触发重排),所以在forEach循环结束后直接读取即可拿到正确尺寸:

wordsArray.forEach((word, index) => {
    $('#adjective').append(`<div style='opacity: ${index === 0 ? 1 : 0};'>${word}</div>`)
})

// 原生方式读取第一个div高度
const targetHeight = $('#adjective div:first')[0].offsetHeight;
// 或用jQuery方法:
// const targetHeight = $('#adjective div:first').height();

console.log('元素高度:', targetHeight);

为什么这两种方法比setTimeout更可靠?

  • setTimeout的执行时机不确定,可能早于浏览器完成重绘,导致读取错误高度;也会引入不必要的延迟。
  • 上述两种方法要么贴合浏览器渲染周期,要么强制触发布局计算,能精准获取元素渲染后的真实尺寸,性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:26:05