您的位置:首页 > Web前端 > JQuery

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

2011-03-14 14:30 731 查看
很高兴,终于使用jquery实现了点击外部链接,更改iframe内容时,iframe的高度自适应问题。

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

两个链接和iframe:

Java代码







<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>

<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代码







<script type="text/javascript">

<!--

$(function(){

$("#c-c-iframe").load(function(){

$(this).height($(this).contents().find("#content").height() + 40);

});

});

-->

</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代码







<script type="text/javascript">

<!--

$(function(){

$("#workArea").load(function(){

var height = $(this).contents().find("#box").height() + 40;

//这样给以一个最小高度

$(this).height( height < 400 ? 400 : height );

});

});

-->

</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")不太好使,高度不准确。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: