jquery.load()使iframe随内容改变而自适应高度

很高兴,终于使用jquery实现了点击外部链接,更改iframe内容时,iframe的高度自适应问题。

失败的测试就不说了,来直接的。

两个链接和iframe:

Java代码 复制代码  收藏代码
  1. <li><a href="selfinfo.jsp" target="c-c-iframe" title="个人信息" >个人信息</a></li>   
  2. <li><a href="modifypass.jsp" target="c-c-iframe" title="修改密码" >修改密码</a></li>   
  3.   
  4. <iframe src="init.jsp" id="c-c-iframe" name="c-c-iframe" width="500px;"  frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>  
<li><a href="selfinfo.jsp" target="c-c-iframe" title="个人信息" >个人信息</a></li>
<li><a href="modifypass.jsp" target="c-c-iframe" title="修改密码" >修改密码</a></li>

<iframe src="init.jsp" id="c-c-iframe" name="c-c-iframe" width="500px;"  frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>



js代码:

Java代码 复制代码  收藏代码
  1. <script type="text/javascript">   
  2. <!--   
  3. $(function(){   
  4.     $("#c-c-iframe").load(function(){          
  5.         $(this).height($(this).contents().find("#content").height() + 40);   
  6.     });   
  7.        
  8. });   
  9. -->   
  10. </script>  
<script type="text/javascript">
<!--
$(function(){
	$("#c-c-iframe").load(function(){		
		$(this).height($(this).contents().find("#content").height() + 40);
	});
	
});
-->
</script>



这里的find("#content")是找出iframe内容文档中的id为content的高度(另外比如find("body")),并设置给iframe,
类似的还可以设置宽度,留给需要的朋友尝试吧。

这样就解决了iframe不会因为内容过大被挡住的问题(因为我设置了scrolling="no")。


PS:基本上我会优先考虑使用iframe来实现无刷新,兼容浏览器的后退按钮;而且使用iframe加载flash是很爽的,不用写什么js调用,object标签,还符合W3C标准。

2008年11月28日17:13:31 ,今天使用过程中根据实际情况进行了一下改良,代码如下:

Java代码 复制代码  收藏代码
  1.     <script type="text/javascript">   
  2. <!--   
  3. $(function(){   
  4.     $("#workArea").load(function(){        
  5.         var height = $(this).contents().find("#box").height() + 40;   
  6. //这样给以一个最小高度   
  7.         $(this).height( height < 400 ? 400 : height );   
  8.     });   
  9.        
  10. });   
  11. -->   
  12. </script>  
	<script type="text/javascript">
<!--
$(function(){
	$("#workArea").load(function(){		
		var height = $(this).contents().find("#box").height() + 40;
//这样给以一个最小高度
		$(this).height( height < 400 ? 400 : height );
	});
	
});
-->
</script>



另发现使用find("body")不太好使,高度不准确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值