前端面试题:iframe详解
2019-08-19 本文已影响0人
令狐张豪
iframe 元素会创建包含另外一个文档的内联框架(即行内框架),简单来说就是把另一个文档用iframe给引进来
比如A页面引入B页面里的内容
A页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
iframe {
width: 300px;
height: 300px;
background-color: red;
border: 0;
}
html * {
margin: 0;
padding: 0;
}
</style>
<body>
<iframe src="./iframe_B.html" frameborder="0" scrolling="no"></iframe>
</body>
</html>
A页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
.box {
width: 300px;
height: 300px;
border: 1px solid black;
}
</style>
<body>
<div class="box">
</div>
</body>
</html>
iframe的一些基本属性:
- frameborder:是否显示边框,0(不显示)
- height:框架作为一个普通元素的高度,建议在使用css设置。
- width:框架作为一个普通元素的宽度,建议使用css设置。
- name:框架的名称,window.frames[name]时专用的属性。
- scrolling:框架的是否滚动。yes,no,auto。
- src:内框架的地址,可以使页面地址,也可以是图片的地址。
- srcdoc , 用来替代原来HTML body里面的内容。但是IE不支持, 不过也没什么卵用
- sandbox: 对iframe进行一些列限制,IE10+支持
iframe 可以跨域吗?
可以,用document.domain解决
举例,网页a(http://www.easonwong.com)和网页b(http://script.easonwong.com),两者都设置document.domain = 'easonwong.com'
(这样浏览器就会认为它们处于同一个域下),然后网页a再创建iframe上网页b,就可以进行通信啦~!
网页a
document.domain = 'easonwong.com';
var ifr = document.createElement('iframe');
ifr.src = 'http://script.easonwong.com';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function(){
let doc = ifr.contentDocument || ifr.contentWindow.document;
// 在这里操纵b.html
};
网页b
document.domain = 'easonwong.com';