如何在Blogger网站实现iframe高度100%并随内容自适应?
Blogger嵌入iframe高度自适应解决方案
先解决基础100%高度无效的问题
现有代码里的height:100%不生效,核心原因是html、body等父元素未设置明确高度,先修改CSS:
html, body { height: 100%; margin: 0; padding: 0; } .container { height: 100%; width: 100%; overflow: hidden; } .item { width: 100%; border: none; /* 移除默认边框优化显示 */ }
实现内容自适应高度(分两种场景)
场景1:你能控制嵌入的外部网站
这是最可靠的方案,利用postMessage跨域传递内容高度:
- 在Blogger页面的HTML中添加监听脚本:
window.addEventListener('message', function(e) { // 仅接收目标网站的消息,保障安全 if (e.origin === 'https://motatwer.website') { const iframe = document.querySelector('.item'); if (iframe) { iframe.style.height = e.data + 'px'; } } }, false);
- 在嵌入的外部页面中添加发送高度的脚本:
// 页面加载完成后发送实际高度 window.addEventListener('load', function() { const pageHeight = document.documentElement.scrollHeight || document.body.scrollHeight; window.parent.postMessage(pageHeight, 'https://fortestonly5.blogspot.com'); }); // 内容动态变化时重新发送高度(可选) window.addEventListener('resize', function() { const pageHeight = document.documentElement.scrollHeight || document.body.scrollHeight; window.parent.postMessage(pageHeight, 'https://fortestonly5.blogspot.com'); });
场景2:无法控制外部网站
受浏览器同源策略限制,无法直接获取iframe内容高度,可用以下变通方法:
- 方法A:允许iframe显示滚动条
直接移除scrolling="no"属性,让iframe内部显示滚动条,用户可滚动查看全部内容:
<div class="container"> <iframe class="item" src="https://motatwer.website/show-compare?first_phone=53&seconde_phone=2"></iframe> </div>
- 方法B:尝试估算高度(准确性有限)
利用iframe的onload事件,尝试获取高度(跨域可能报错,需兼容):
document.querySelector('.item').addEventListener('load', function() { setTimeout(() => { try { const height = this.contentDocument.documentElement.scrollHeight; this.style.height = height + 'px'; } catch (err) { // 跨域失败时设置一个足够大的高度 this.style.height = window.innerHeight * 2.5 + 'px'; } }, 1000); // 延迟执行确保内容加载完成 });
内容的提问来源于stack exchange,提问作者motatwer.com
相关产品推荐
相关产品推荐

