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

如何获取<object>标签内部内容完整高度并动态设置其高度

解决标签加载外部HTML时动态设置高度的问题

核心问题

用<object>嵌入外部HTML时,固定高度设置容易出现滚动条,关键在于获取嵌入内容的实际高度后动态调整<object>的高度。


同域场景解决方案

如果嵌入的HTML和主页面属于同一域名,可以直接访问<object>内部的文档对象来获取高度:

  1. 给<object>添加ID并移除固定高度:
<object id="externalObj" data="test.html" type="text/html" style="width:100%;border:none;"></object>
  1. 添加JavaScript监听加载完成事件,获取并设置高度:
const obj = document.getElementById('externalObj');
obj.onload = function() {
  // 获取嵌入内容的完整滚动高度
  const contentHeight = obj.contentDocument.body.scrollHeight;
  // 动态设置object高度,可额外加少量缓冲避免内容溢出
  obj.style.height = `${contentHeight + 10}px`;
};

说明:scrollHeight返回包含所有滚动内容的高度,比offsetHeight更适合获取完整内容高度;添加10px缓冲是为了避免浏览器渲染差异导致的微小溢出。


跨域场景解决方案

如果嵌入的HTML属于不同域名,受同源策略限制无法直接访问内部文档,需要通过postMessage跨域通信传递高度:

主页面(嵌入<object>的页面)代码

<object id="externalObj" data="https://www.second-domain.com/test.html" type="text/html" style="width:100%;border:none;"></object>

<script>
// 监听跨域消息
window.addEventListener('message', function(event) {
  // 验证消息来源,防止恶意请求
  if (event.origin !== 'https://www.second-domain.com') return;
  
  const obj = document.getElementById('externalObj');
  // 根据子页面传递的高度设置object高度
  obj.style.height = `${event.data + 10}px`;
});
</script>

被嵌入的外部HTML页面(https://www.second-domain.com/test.html)代码

window.onload = function() {
  // 获取当前页面的完整高度
  const pageHeight = document.body.scrollHeight;
  // 向主页面发送高度数据,指定主页面域名确保安全
  parent.postMessage(pageHeight, 'https://your-main-domain.com');
};

说明:

  • 必须验证event.origin,只处理信任域名的消息,避免安全风险。
  • parent.postMessage的第二个参数指定主页面域名,不要用*,防止消息泄露给无关页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:32:46