iframe

什么是iframe?

iframe 元素会创建包含另外一个文档的内联框架(即行内框架)。
就是在不刷新页面的情况下,在当前页面中插入其他页面,和react和vue的渲染机制有些相似

iframe注意事项

1、在“跨域”或者“打开的是本地文件”的情况下,iframe是获取不到contentWindow子对象的,这对设置高度自适应来说有了难度。跨域的话就解决一下跨域问题即可。本地文件的话,通过nginx部署到localhost即可。
2、设置 高度自适应 思路,利用定时器,去不间断获取iframe的contentWindow的子页面高度,再将<iframe></iframe>的高度设置为子页面高度即可,同时需设置frameborder="0",scrolling="no"

使用(点击a链接切换不同的iframe页面)

<div>
    <a href="./eat.html" target="iframetest">零食</a>   //iframe跳转需要设置:a标签的href,target 以及 iframe标签的name
    <a href="./clothes.html" target="iframetest">衣服</a>
    <a href="./play.html" target="iframetest">娱乐</a>
</div>
<div>
    <iframe src="./research.html" name="iframetest" class="iframetest" id="iframetest" width="100%" height="200" frameborder="0" scrolling="no"></iframe>
</div>

使用(高度自适应)——必备条件:不可以跨域,不可以是本地文件(若跨域或为本地网页,则iframe高度自适应不生效)

function initIframe(){  //高度自适应函数
    var ifm= document.getElementById("iframetest");
    try{
        let ha = ifm.contentWindow.document.body.scrollHeight;
        let hb = ifm.contentWindow.document.documentElement.scrollHeight;
        let hc = Math.min(ha, hb);
        ifm.height = hc;
        // console.log(hc);
    }catch (ex){}
}

如何执行:
方式一:定时触发高度自适应函数,以保证iframe高度改变后,能及时适应新高度
window.setInterval("initIframe()", 300); 

方式二:等iframe加载完毕后,执行高度自适应函数 (推荐这种方式) 
document.getElementById('iframetest').onload=function(){      
     initIframe()
}; 

知识点(如何判断元素是否加载完毕)

window.onload=function(){}    //dom加载完毕后执行函数

document.getElementById('demo').onload=function(){}   //id为demo的元素加载完毕后执行函数

posted @ 2019-12-02 17:06  huihuihero  阅读(1112)  评论(0编辑  收藏  举报