HTML DOM 对iframe排版
2025-04-24
18
参考资料
HTML DOM iframe 排版
iframe 标签
<iframe>
标签用于在网页中嵌入另一个文档。
基本语法
<iframe src="URL" width="px" height="px" frameborder="0"></iframe>
主要属性
src
: 指定要嵌入的文档URLwidth
: 设置iframe宽度height
: 设置iframe高度frameborder
: 是否显示边框(0为无边框,1为有边框)name
: 为iframe命名sandbox
: 安全限制选项allowfullscreen
: 是否允许全屏
用法
基本用法
<iframe src="https://example.com" width="600" height="400"></iframe>
命名iframe
<iframe name="myFrame" src="page.html"></iframe> <a href="newpage.html" target="myFrame">在iframe中加载</a>
动态修改内容
document.getElementById('myFrame').src = 'newpage.html';
CSS 扩展
样式控制
iframe { border: none; /* 移除边框 */ margin: 0; padding: 0; display: block; overflow: hidden; /* 隐藏滚动条 */ } /* 响应式iframe */ .responsive-iframe { position: relative; padding-bottom: 56.25%; /* 16:9 比例 */ height: 0; overflow: hidden; } .responsive-iframe iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
功能实例
嵌入视频
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen> </iframe>
嵌入地图
<iframe src="https://maps.google.com/maps?q=New+York&output=embed" width="600" height="450" frameborder="0" style="border:0"> </iframe>
响应式iframe
<div class="responsive-iframe"> <iframe src="content.html"></iframe> </div>
DOM 操作
获取iframe内容
var iframe = document.getElementById('myFrame'); var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
跨域通信
// 父页面 window.addEventListener('message', function(e) { if(e.origin !== 'https://child-domain.com') return; console.log('收到消息:', e.data); }); // iframe内 parent.postMessage('Hello parent!', 'https://parent-domain.com');
注意事项
跨域限制:同源策略会影响iframe与父页面的交互
性能影响:过多iframe会影响页面加载性能
移动设备适配:需要特别处理移动设备上的显示
安全性:使用
sandbox
属性限制iframe权限
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。