H5实现iframe
H5 中使用 iframe 的基本方法
在 HTML5 中,<iframe> 元素用于嵌入另一个网页或文档。通过设置 src 属性指定要嵌入的内容 URL。
<iframe src="https://example.com" width="600" height="400"></iframe>
设置 iframe 的尺寸和边框
通过 width 和 height 属性控制 iframe 的尺寸,单位为像素或百分比。使用 frameborder 属性控制边框显示(0 为无边框,1 为有边框)。
<iframe src="https://example.com" width="100%" height="300" frameborder="0"></iframe>
添加 iframe 的标题和安全性设置
为提升可访问性,建议通过 title 属性为 iframe 添加描述。使用 sandbox 属性限制 iframe 的权限,增强安全性。

<iframe src="https://example.com" title="Example Website" sandbox="allow-scripts"></iframe>
响应式 iframe 的实现
通过 CSS 或直接设置样式,使 iframe 适应不同屏幕尺寸。以下示例使用 CSS 实现响应式布局。
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
<iframe
src="https://example.com"
style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"
frameborder="0"
></iframe>
</div>
跨域通信与 iframe
若需与 iframe 内嵌页面通信,需确保目标页面支持跨域。使用 postMessage 实现双向通信。

<iframe id="myFrame" src="https://example.com"></iframe>
<script>
const frame = document.getElementById('myFrame');
frame.contentWindow.postMessage('Hello', 'https://example.com');
</script>
动态加载 iframe 内容
通过 JavaScript 动态修改 src 属性或创建 iframe 元素,实现内容动态加载。
<button onclick="loadIframe()">Load Iframe</button>
<div id="iframeContainer"></div>
<script>
function loadIframe() {
const container = document.getElementById('iframeContainer');
container.innerHTML = '<iframe src="https://example.com" width="600" height="400"></iframe>';
}
</script>
处理 iframe 加载事件
监听 load 事件以检测 iframe 内容是否加载完成,便于执行后续操作。
<iframe id="myFrame" src="https://example.com" onload="iframeLoaded()"></iframe>
<script>
function iframeLoaded() {
console.log('Iframe content loaded.');
}
</script>




