zoukankan      html  css  js  c++  java
  • iframe跨域自适应高度

    思路:

    现有主界面main在域a下,被嵌套页面B在域b下,被嵌套页面B又嵌套一个在域a下的中介页面A。

    当用户打开浏览器访问mail.html的时候载入B,触发B的onload事件获取其自身高度,然后B载入A,并将高度值作为参数赋值给A的location对象。

    这样A就可以通过location.hash获得B的高度。(location是javascript里边管理地址栏的内置对象,比如location.href就管理页面的url,用location.href=url就可以直接将页面重定向url。

    而location.hash则可以用来获取或设置页面的标签值。比如http://domain/#admin的location.hash="#admin"。利用这个属性值可以做一些非常有意义的事情。)。

    由于A和main页面同域,所以可以修改main的dom节点属性,从而达到我们设置iframe标签高度的目的。

    iframe主页面:main.html

    <iframe id="iframeB"  name="iframeB" src="www.b.com/B.html" width="100%" height="auto" scrolling="no" frameborder="0"></iframe>

    iframe嵌套页面:B.html

    <iframe id="iframeA" name="iframeA" src="" width="0" height="0" style="display:none;" ></iframe>
     
    <script type="text/javascript">
     
    function sethash(){
     
        hashH = document.documentElement.scrollHeight; //获取自身高度
     
        urlC = "www.a.com/A.html"; //设置iframeA的src
     
        document.getElementById("iframeA").src=urlC+"#"+hashH; //将高度作为参数传递
     
    }
     
    window.onload=sethash;
     
    </script>

    中介页面:A.html

    <script> 
    function  pseth() { 
        var iObj = parent.parent.document.getElementById('iframeB');//A和main同域,所以可以访问节点 
        iObjH = parent.parent.frames["iframeB"].frames["iframeA"].location.hash;//访问自己的location对象获取hash值 
        iObj.style.height = iObjH.split("#")[1]+"px";//操作dom 
    } 
    pseth(); 
    </script>
  • 相关阅读:
    每日日报46
    每日日报45
    每日日报44
    每日日报43
    每日日报42
    每日日报41
    每日日报40
    每日日报之一周总结
    每日日报
    每日日报
  • 原文地址:https://www.cnblogs.com/fan-fan/p/3488155.html
Copyright © 2011-2022 走看看