轉自:http://caiceclb.iteye.com/blog/281102
很高興,終於使用jquery實現了點擊外部鏈接,更改iframe內容時,iframe的高度自適應問題。
失敗的測試就不說了,來直接的。
兩個鏈接和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代碼:
- <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 ,今天使用過程中根據實際情況進行了一下改良,代碼如下:
- <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")不太好使,高度不准確。