iframe嵌套界面自适应,可高度自由收缩

Yoth Blog

iframe嵌套界面自适应,可高度自由收缩

Upcoming Sessions
Table of Contents
    Add a header to begin generating the table of contents

    最近在用RT-Theme 18做720yun.com网页时需要使iframe高度自适应,以提高用户体验,网上找了挺多都很复杂,后来在csdn看到的这段代码简介而有效,故此记录下,感谢博主。

    HTML

    				
    					<div class="main_page">
    	 <iframe scrolling="no" id="main" name="main" frameborder="0"  src="" 
            style="min-height:600px;width:100%;height:100%;"></iframe>
    </div>
    				
    			

    JS

    				
    					<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
      }
      //根据ID获取iframe对象
      var ifr = document.getElementById('main')
      ifr.onload = function() {
      	  //解决打开高度太高的页面后再打开高度较小页面滚动条不收缩
      	  ifr.style.height='0px';
          var iDoc = ifr.contentDocument || ifr.document
          var height = calcPageHeight(iDoc)
          if(height < 850){
          	height = 850;
          }
          ifr.style.height = height + 'px'
      }
    </script>
    				
    			
    Facebook
    Twitter
    LinkedIn

    Maybe You Like

    WordPress

    Astra

    RT Theme

    Scroll to Top