由于浏览器安全原因以下的contentDocument contentWindow 对象必须起一个页面服务(通过域名或ip地址来访问)并且得保证父页面与子页面是在同一域名下,不然是会报错的

contentDocument 可以获得iframe子窗口的document对象,兼容ie8+

contentWindow    这是个只读属性,返回指定的iframe的窗口对象

iframe加载完毕之后通过contentDocument 或者 contentWindow 这二个对象来获取iframe子页面的内容高度,从而来设置iframe的高度.再给iframe设置高度时子页面的默认样式margin要记得清除(不清楚是会有这个margin大小的误差的,有这个margin的话子页面的内容就无法全部显示出来了).

iframe的父页面

<iframe scrolling="no" ></iframe>

        <script type="text/javascript">
            //根据ID获取iframe对象
            var ifr = document.getElementById('main');

            ifr.onload = function() {
                //解决滚动条不收缩
                ifr.style.height = 0+'px';

                var iDoc = ifr.contentDocument || ifr.contentWindow.document;
                
                var height = iDoc.documentElement.clientHeight || iDoc.body.clientHeight;

                console.log(iDoc.documentElement.clientHeight,iDoc.body.clientHeight);
                
                ifr.style.height = height + 'px';
                console.log(height);   
            }
</script> 

相关文章:

  • 2021-12-22
  • 2021-12-12
  • 2021-11-09
  • 2022-12-23
  • 2021-09-06
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
  • 2021-12-04
相关资源
相似解决方案