jquery实现iframe自适应高度

本文介绍如何使用JavaScript让iframe元素根据其内容自适应高度,并提供了设置最小固定高度的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、iframe自适应页面高度

      首先需要给iframe设置一个id,不需要滚动条则加上scrolling="no"

      然后加上一个onload事件

function iFrameHeight(iframe) {   
	var ifm= document.getElementById(iframe.id);   
	var subWeb = document.frames ? document.frames[iframe.id].document : ifm.contentDocument;   
	if(ifm != null && subWeb != null) {
	   ifm.height = subWeb.body.scrollHeight;
	   ifm.width = subWeb.body.scrollWidth;
	}   
} 

<iframe src=' ' width='100%'  id="compInfo" frameborder='0'scrolling="no"  onload="iFrameHeight(this)"></iframe>


2、若需要iframe固定一个高度,超过这个高度才自适应

function iFrameHeightContact(iframe) {   
	var ifm= document.getElementById(iframe.id);   
	var subWeb = document.frames ? document.frames[iframe.id].document : ifm.contentDocument;   
	if(ifm != null && subWeb != null) {
		var ifmHeight = subWeb.body.scrollHeight;
		var ifmWidth = subWeb.body.scrollWidth;
		if(ifmHeight<400){
			ifm.height = 400;
			ifm.width = ifmWidth;
		} else {
			ifm.height = ifmHeight;
			ifm.width = ifmWidth;
		}
	   
	}   
} 

<iframe src=' ' width='100%'  id="compInfo" frameborder='0'scrolling="no"  onload="iFrameHeight(this)"></iframe>

* 400则为你想要固定的高度



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值