一、改變iframe頁面的內容
如果需要使用iframe高度隨內容改變,我們需要在iframe載入之前確定iframe要載入的內容大小。因此,我們需要做出如下改變:
1. 在iframe內的內容改變時,通知父頁面進行高度調整。
我們可以在iframe內使用以下代碼:
window.parent.postMessage({ 'type': 'resize', 'height': document.body.offsetHeight }, '*');
在父頁面內使用如下代碼進行響應:
window.addEventListener('message', function(event) { if (event.data.type === 'resize') { document.querySelector('iframe').style.height = event.data.height + 'px'; } });
2. 在iframe外的腳本文件中通過ajax獲取iframe要載入的內容大小。
例如,在jQuery中可以使用如下代碼:
$.ajax({ url: 'iframe.html', type: 'GET', success: function(response) { $('iframe').height($(response).height()); } });
二、獲取iframe內容高度
在第一部分中,我們已經講到如何實現在iframe內部通知父頁面進行高度調整。但是,我們也需要知道iframe內部內容的高度大小。以下是獲取iframe內容高度的方法:
1. 使用window.onload事件
當iframe內部內容載入完成後,window.onload事件會被觸發。我們可以通過下列代碼獲取iframe內部內容的高度:
<iframe id="myIframe" src="iframe.html" onload="resizeIframe()"></iframe>
function resizeIframe() {
var iframe = document.getElementById('myIframe');
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
}
2. 使用MutationObserverAPI
MutationObserver API能夠觀察DOM樹的變化,並在有變化時調用特定函數。我們可以利用這個API去監控iframe內部內容的變化。
以下是一個使用MutationObserverAPI的代碼範例:
<iframe id="myIframe" src="iframe.html"></iframe>
var iframe = document.getElementById('myIframe');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
});
});
observer.observe(iframe.contentWindow.document.body, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
三、結合兩種方法
將兩個方法結合起來,可以實現實時更改iframe高度,以下是示例代碼:
<iframe id="myIframe" src="iframe.html" onload="resizeIframe()"></iframe>
var iframe = document.getElementById('myIframe');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
});
});
observer.observe(iframe.contentWindow.document.body, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
function resizeIframe() {
$.ajax({
url: 'iframe.html',
type: 'GET',
success: function(response) {
iframe.style.height = $(response).height() + 'px';
}
});
}
四、使用第三方庫
當然我們也可以使用第三方庫來幫助實現這個功能。目前比較常見的庫是iframe-resizer和Pym.js。以下是一個使用Pym.js的代碼範例:
<div id="parent">
<iframe id="myIframe" src="iframe.html"></iframe>
</div>
var pymParent = new pym.Parent('parent', 'iframe.html');
五、總結
本文中,我們介紹了如何使用多種方法實現iframe高度隨內容改變。我們可以選擇最適合自己項目的解決方案來使用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/292040.html