h5实现frame
使用 iframe 嵌入外部内容
在 HTML5 中,可以通过 <iframe> 标签嵌入其他网页或文档。该标签支持多种属性用于控制框架的行为和外观。
<iframe src="https://example.com" width="600" height="400" frameborder="0"></iframe>
src 属性指定要嵌入的页面 URL,width 和 height 控制框架尺寸,frameborder 控制是否显示边框(0 为无边框)。
设置 iframe 的 sandbox 属性
为增强安全性,HTML5 新增了 sandbox 属性,用于限制 iframe 的权限。可以防止嵌入的页面执行某些可能有害的操作。
<iframe src="external.html" sandbox="allow-scripts allow-same-origin"></iframe>
sandbox 可配置多个值:allow-forms 允许表单提交,allow-scripts 允许执行脚本,allow-same-origin 允许同源请求。
响应式 iframe 设计
通过 CSS 实现 iframe 的响应式布局,使其能适应不同屏幕尺寸。常用方法是使用 padding-bottom 技巧保持宽高比。
<div class="iframe-container">
<iframe src="video.html" allowfullscreen></iframe>
</div>
.iframe-container {
position: relative;
width: 100%;
padding-bottom: 56.25%; /* 16:9 宽高比 */
height: 0;
}
.iframe-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
使用 srcdoc 属性嵌入 HTML 内容
srcdoc 属性允许直接在 iframe 中嵌入 HTML 代码,无需外部文件。适用于动态生成内容的场景。
<iframe srcdoc="<h1>Hello World</h1><p>This is embedded HTML content.</p>" width="300" height="150"></iframe>
跨域通信技术
当 iframe 与父页面不同源时,可使用 postMessage API 实现安全通信。父页面和 iframe 都需要监听 message 事件。

<!-- 父页面代码 -->
<iframe id="childFrame" src="https://child-domain.com"></iframe>
<script>
const frame = document.getElementById('childFrame');
frame.contentWindow.postMessage('Hello from parent', 'https://child-domain.com');
window.addEventListener('message', (event) => {
if (event.origin !== 'https://child-domain.com') return;
console.log('Received:', event.data);
});
</script>
<!-- iframe 页面代码 -->
<script>
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent-domain.com') return;
console.log('Received:', event.data);
event.source.postMessage('Hello back!', event.origin);
});
</script>

