阅读量:145
有以下几种方法可以实现iframe的高度自适应:
- 使用JavaScript动态调整高度:通过JavaScript的方法来获取iframe中内容的实际高度,然后将该高度赋值给iframe的height属性。
[removed]
function resizeIframe() {
var iframe = document.getElementById('myIframe');
var iframeHeight = iframe.contentWindow.document.body.scrollHeight;
iframe.style.height = iframeHeight + 'px';
}
[removed]
<iframe id="myIframe" src="yourPage.html" onload="resizeIframe()"></iframe>
- 使用CSS的calc()函数:通过CSS的calc()函数来计算iframe的高度,将iframe的高度设置为100%减去固定的高度。
<style>
#myIframe {
height: calc(100% - 50px); /* 50px为固定高度 */
}
</style>
<iframe id="myIframe" src="yourPage.html"></iframe>
- 使用jQuery的resize()方法:通过jQuery的resize()方法来自动调整iframe的高度。
[removed]"https://code.jquery.com/jquery-3.6.0.min.js">[removed]
<script>
$(document).ready(function() {
$('#myIframe').on('load', function() {
$(this).height($(this).contents().height());
});
});
</script>
<iframe id="myIframe" src="yourPage.html"></iframe>