iframe __veblen
iframe的一些缺点一直被人诟病,就像生活一样,一个缺点便可以颠覆认知,哪有那么多的理所当然,要什么自行车?
iframe在很多开发场景都是非常适用的,例如saas应用、文件无跳转上传、下载等! 接下来一块领略iframe的妙用(遵循同源,请在服务器环境测试练习):
1.基础用法:
iframe是一个内联框架被用来在当前 HTML 文档中嵌入另一个文档。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>清风笔记</title>
</head>
<body>
<iframe src="child.html">
<p>您的浏览器不支持 iframe 标签。</p>
</iframe>
</body>
</html>
对于不支持的浏览器,可以在标签内部插入提示内容 ,src属性指向iframe访问路径。
2.父子页面访问:
-
2.1父访问子
document对象
- iframeElement.contentDocument; // chrome
- iframeElement.contentDocument; // firefox
- iframeElement.contentWindow.document; // (ie没有iframeElement.contentDocument属性)
var getIframeDocument = iframeElement.contentDocument || iframeElement.contentWindow.document;//兼容方式
能够访问document对象了,那操作元素节点等等相关也就不在话下了。
-
2.2 父访问子
window对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>清风笔记</title>
</head>
<body>
<iframe src="child.html" height="500" width="500" name="iframename" id="iframe">
</iframe>
</body>
<script>
var iframe=document.getElementById("iframe");
console.log(iframe.contentWindow) //获取iframe页面window对象
</script>
</html>
-
2.3子访问父
document、window对象
window.parent //访问父window对象
window.parent.document //访问父document对象
-
2.4 方法互相访问
因为一定有对应方法访问
window对象,所以function可以借助window对象进行访问,以下是综合案例: -
parent.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>清风笔记-parent</title>
</head>
<body>
<iframe src="child.html" height="500" width="500" frameborder="0" name="iframename" id="iframe">
<p>您的浏览器不支持iframe 亲!</p>
</iframe>
<button id="parent_btn">触发child_fn</button>
</body>
<script>
var iframeElement=document.getElementsByName("iframename")[0]
var iframeDocument = iframeElement.contentDocument||iframeElement.contentWindow.document;
var iframeWindow = iframeElement.contentWindow;
parent_btn.onclick=function(){
iframeWindow.fn();
}
function fn(){
alert("子页面触发父页面方法!")
}
</script>
</html>
-
child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>清风笔记-child</title>
</head>
<body>
<button id="child_btn">触发parent_fn</button>
</body>
<script>
child_btn.onclick=function(){
window.parent.fn();
}
function fn(){
alert("父页面触发子页面方法!")
}
</script>
</html>
最后,再来看一下iframe的优缺点,在开发场景中权衡利弊:
iframe的优点:
-
① iframe能够原封不动地把嵌入的网页展现出来。
-
② 如果有多个网页调用iframe,只需要修改iframe的内容,就可以实现对调用iframe的每一个页面内容的更改,方便快捷。
-
③ 网页如果为了统一风格,头部和版本都是一样的,就可以写成一个页面,用iframe来嵌套,可以增加代码的可重用性。
-
④ 如果遇到加载缓慢的第三方内容,如图标和广告等,可以用iframe来解决。
iframe的缺点:
-
① 会产生很多页面,不容易管理。
-
② 在几个框架中都出现上下、左右滚动条时,这些滚动条除了会挤占已经非常有限的页面空间外,还会分散访问者的注意力。
-
③ 使用框架结构时,必须保证正确设置所有的导航链接,否则会给访问者带来很大的麻烦。比如被链接的页面出现在导航框架内,这种情况下会导致链接死循环。
-
④ 很多的移动设备(PDA手机)无法完全显示框架,设备兼容性差。
-
⑤ iframe框架页面会增加服务器的http请求,对SEO不友好,对于大型网站是要慎重的。
加油!










网友评论