首页 期权学习期权知识正文

html的iframe高度自适应三种写法

xiaojiucai 期权知识 2020-08-18 380 0

想到的一种办法是,在父页面里获取子页面的高度,在父页面onlod里把获取到子页面的高度赋值给父页面iframe标签,不过这种方法感觉不是很好,因为浏览器兼容性不好,获取不到高度

这种方法有两种写法

1、

<script type="text/javascript">
  // 计算页面的实际高度,iframe自适应会用到
  function calcPageHeight(doc) {
      var cHeight = Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
      var sHeight = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight)
      var height  = Math.max(cHeight, sHeight)
      return height
  }
  var ifr = document.getElementById('ifr')
  ifr.onload = function() {
      var iDoc = ifr.contentDocument || ifr.document
      var height = calcPageHeight(iDoc)
      ifr.style.height = height + 'px'
  }
</script>

2、

<script>
    // 计算页面的实际高度,iframe自适应会用到
    function calcPageHeight(doc) {
        var cHeight = Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
        var sHeight = Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight)
        var height  = Math.max(cHeight, sHeight)
        return height
    }
    window.onload = function() {
        var height = calcPageHeight(document)
        parent.document.getElementById('ifr').style.height = height + 'px'     
    }
</script>

3、还有一种是兼容性比较好的

<iframe src="http://www.fufuok.com/" id="iframepage" name="iframepage" frameBorder=0 scrolling=no width="100%" onLoad="iFrameHeight()" ></iframe>Javascript代码: 
<script type="text/javascript" language="javascript"> 
function iFrameHeight() { 
var ifm= document.getElementById("iframepage"); 
var subWeb = document.frames ? document.frames["iframepage"].document : ifm.contentDocument; 
if(ifm != null && subWeb != null) { 
ifm.height = subWeb.body.scrollHeight; 
} 
} 
</script>

原文链接:https://www.qiquanji.com/post/7672.html

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

微信扫码关注

更新实时通知

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

评论