html iframe高度自適應


想到的一種辦法是,在父頁面里獲取子頁面的高度,在父頁面onlod里把獲取到子頁面的高度賦值給父頁面iframe標簽,不過這種方法感覺不是很好,因為瀏覽器兼容性不好,獲取不到高度

這種方法有兩種寫法

<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>
<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>

 

還有一種是兼容性比較好的

<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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM