前端博文

前端面试题: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的一些基本属性:

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';
上一篇 下一篇

猜你喜欢

热点阅读