<iframe>标签用于在网页里面嵌入其他网页。
<iframe>
<iframe>标签生成一个指定区域,在该区域中嵌入其他网页。它是一个容器元素,如果浏览器不支持<iframe>,就会显示内部的子元素。
<iframe src="https://www.example.com" width="100%" height="500" frameborder="0" allowfullscreen sandbox> <p><a href="https://www.example.com">点击打开嵌入页面</a></p> </iframe>
上面的代码在当前网页嵌入https://www.example.com,显示区域的宽度是100%,高度是500像素。如果当前浏览器不支持<iframe>,则会显示一个链接,让用户点击。
https://www.example.com
100%
500
浏览器普遍支持<iframe>,所以内部的子元素可以不写。
<iframe>的属性如下。
allowfullscreen
frameborder
0
1
src
width
height
sandbox
importance
high
low
auto
name
<a>
<form>
<base>
target
referrerpolicy
Referer
嵌入的网页默认具有正常权限,比如执行脚本、提交表单、弹出窗口等。如果嵌入的网页是其他网站的页面,你不了解对方会执行什么操作,因此就存在安全风险。为了限制<iframe>的风险,HTML 提供了sandbox属性,允许设置嵌入的网页的权限,等同于提供了一个隔离层,即“沙箱”。
sandbox可以当作布尔属性使用,表示打开所有限制。
<iframe src="https://www.example.com" sandbox> </iframe>
sandbox属性可以设置具体的值,表示逐项打开限制。未设置某一项,就表示不具有该权限。
allow-forms
allow-modals
window.alert()
allow-popups
window.open()
allow-popups-to-escape-sandbox
allow-orientation-lock
allow-pointer-lock
allow-presentation
allow-same-origin
allow-scripts
allow-storage-access-by-user-activation
allow-top-navigation
allow-top-navigation-by-user-activation
allow-downloads-without-user-activation
注意,不要同时设置allow-scripts和allow-same-origin属性,这将使得嵌入的网页可以改变或删除sandbox属性。
<iframe>指定的网页会立即加载,有时这不是希望的行为。<iframe>滚动进入视口以后再加载,这样会比较节省带宽。
loading属性可以触发<iframe>网页的懒加载。该属性可以取以下三个值。
loading
lazy
eager
<iframe src="https://example.com" loading="lazy"></iframe>
上面代码会启用<iframe>的懒加载。
有一点需要注意,如果<iframe>是隐藏的,则loading属性无效,将会立即加载。只要满足以下任一个条件,Chrome 浏览器就会认为<iframe>是隐藏的。
<iframe>的宽度和高度为4像素或更小。 样式设为display: none或visibility: hidden。 使用定位坐标为负X或负Y,将<iframe>放置在屏幕外。
display: none
visibility: hidden
X
Y
<iframe
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8