如何获取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