如何獲取iframe高度並設置自適應


不使用vue對靜態頁進行組建化封裝,第一個就想到了iframe。但是嵌入后,iframe的高度並不是自適應的,需要獲取到子頁面的高度並在父頁面中進行設置。

兩個頁面,parent.html,child.html

在parent.html中:

<iframe id="ifra" name="ifra" width="100%" scrolling="no" frameborder="no" src="child.html"></iframe>

JS:

  var frame = document.getElementById('ifra')
        window.addEventListener('message', function(e) {
            frame.style.height = e.data.height + 'px'
            frame.style.width = e.data.width + 'px'
        })

child.html:

document.addEventListener('DOMContentLoaded', function() {
        var tbody = document.body
        var width = tbody.clientWidth
        var height = tbody.clientHeight
        window.parent.postMessage({
            height: height,
            width: width
        }, '*')
    }, false)

這樣就大致好了。


免責聲明!

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



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