关于iframe

一、为何使用iframe?
一般用来包含别的页面,例如我们可以在我们自己的网站页面加载别人网站的内容

<body>
    <div class='btn' >
        <input id='btn' type="button" value='加载第1个html文件'/>
        <input type="button" value='加载第2个html文件'/>
    </div>
    <iframe src='model1.html' class='con' id='frameBox'></iframe>
</body>

二、如何在当前页面调用iframe中的标签和内容?
contentWindow、contentDocument

<script>
    var frameBox = document.getElementById('frameBox');
    var btn = document.getElementById('btn');
    btn.onclick = function(){
        var frameTit = frameBox.contentWindow.document.getElementsByTagName('h1');
        console.log(frameTit[0].innerHTML);        
    }
</script>

注意由于JS有执行顺序 ,因此不要写成如下样子:

<script>
    var frameBox = document.getElementById('frameBox');
    var frameTit = frameBox.contentWindow.document.getElementsByTagName('h1');
    console.log(frameTit[0].innerHTML);        
</script>

另外,var frameTit = frameBox.contentWindow.document.getElementsByTagName(‘h1’);等价于var frameTit = frameBox.contentDocument.getElementsByTagName(‘h1’);但是,contentDocument不兼容IE6和7

三、如何在iframe中调用当前页面的内容?
window.parent、window.top
window.parent.document.getElementsByTagName(‘div’);

window.top.document.getElementsByTagName(‘div’);

四、检测iframe的内容是否加载完成?

<script>
    var newFrame = document.createElement('iframe');
    newFrame.src = 'model1.html';
    document.body.appendChild(newFrame);

    newFrame.onload = function(){
        alert('已经加载完成iframe框架');
    }
</script>

IE下的iframe的onload事件我们需要使用绑定的方式,不然不能够生效。也就是把onload的书写方式调整为attachEvent的书写方式:

newFrame.attachEvent('onload', function(){
    alert('已经加载完成iframe框架');
});

五、防止别人使用自己的网站钓鱼?
为别电泳的iframe文件(自己的网站),添加如下代码:

if (window!=window.top) {
    window.top.location.href = window.location.href;
};

另外:
1. iframe可用于解决跨域问题
2. iframe不利于SEO

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值