vue項目中使用iframe嵌入靜態頁面,動態獲取靜態頁面的高度賦值給iframe的高度


vue項目中使用iframe嵌入靜態頁面的時候,會給iframe一個高度,內容超過這個高度時會產生滾動條,但是不想要滾動條,希望iframe的高度是內容高度,那么來一起學習吧。

    iframe嵌入的靜態圖(初始圖,希望去掉滾動條):

1.在.vue文件中引入iframe,動態給iframe添加高度

  

      path是靜態文件路徑,docHeight是iframe的高度

2.在data中定義iframe的高度

     

3.在methods中定義一個方法獲取靜態頁面的高度

    

 4.在mounted中監聽調用methods中定義的方法

 

5.獲取文本高度   6.監聽文本高度的變化並且將文本高度傳遞給.vue文件

 7.最終效果圖(沒有滾動條了,並且iframe的高度等於靜態頁面的高度)

 .js代碼如下:

var height = "";
function onElementHeightChange(elm, callback) {
    let lastHeight = elm.scrollHeight;
    let newHeight = null ;
    (function run() {
        newHeight = elm.scrollHeight;
        if (lastHeight != newHeight)
            callback(lastHeight)
        lastHeight = newHeight

        if (elm.onElementHeightChangeTimer)
            clearTimeout(elm.onElementHeightChangeTimer)

        elm.onElementHeightChangeTimer = setTimeout(run, 300)
    })()
}
// 監聽body高度變化
onElementHeightChange(document.getElementById("content"), function(h) {
    height = document.getElementById("content").scrollHeight; //獲取文本高度
    window.addEventListener('message', submit());  // 向父頁面傳值
})
function submit() {
    // 向父vue頁面發送信息
    window.parent.postMessage({
        data: {
            code: "success",
            test: height
        }
    }, '*');
}
window.onload = function() {
    height = document.getElementById("content").scrollHeight;
    window.addEventListener('message', submit());
}

 


免責聲明!

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



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