Vue-iframe嵌入页自适应

发布时间 2023-11-17 16:33:15作者: 忙着可爱呀~

Iframe嵌入页自适应方法

/* iframe自适应
    config: {
        iframeId: '',              // iframe id/class
        iframeBodyId: '',          // iframe内 包裹元素 id/class
        bodyId: '.main-container', // 包裹iframe最外层元素 id/class
        unit: ''                   // iframe高度单位,默认 px
    }
*/ 

function iframeAdapted (config) {
    var config = JSON.parse(JSON.stringify(config))
    var size = 0,appHeight = 0,bodyHeight = 0,interval = '';
    var iframe = document.querySelector(config.iframeId)
    config.unit = config.unit || 'px'
    // onresize 
    window.onresize = function () {
        iframeHeightSet(iframe)
    }

    // onscroll
    window.onscroll = function () {
        iframeHeightSet(iframe)
    }

    // onload
    window.onload = function () {
        interval = setInterval(function () {
            size += 1
            iframeHeightSet(iframe)
            if (size > 5) clearInterval(interval)
        }, 500)
    }

    // 设置iframe
    var iframeHeightSet = function (iframe) {
        if (iframe) {
            var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow
            var app = iframeWin.document.querySelector(config.iframeBodyId)
            var body = parent.document.querySelector(config.bodyId)
            if (app) {
                if (appHeight == app.offsetHeight) return false
                appHeight = app.offsetHeight
                bodyHeight = body.offsetHeight
                if (!appHeight) return false
                if (appHeight > bodyHeight) {
                    iframe.style.height = appHeight + config.unit
                } else {
                    iframe.style.height = bodyHeight + config.unit
                }
            }
        }
    }
}