A JavaScript Fancier

伟大的javascript技术研究中...

  IT博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  304 随笔 :: 0 文章 :: 479 评论 :: 0 Trackbacks


     对于iframe高度自适应的问题,网上已经被讨论n次了,一般通过在iframe加载完毕时访问iframe内页body的offsetHeight和offsetWidth然后更新iframe的高宽来实现。
    今日遇到的自适应问题与以往有一些不同,这次的src是一张图片,而且是一张大小不确定的图片(从数据库取出来的数据生成的),在此使用以往的方式似乎就没有那么灵验了。突然想到img标记的高宽是可以获取到的。于是突然有了思路。

解决办法如下:
先动态生成一个img元素,在iframe页面加载完成时(onload)将其src赋给img标记,然后获取该img的高宽,再动态修改iframe高宽即可,同时不要忘了设定iframe页面body的margin和padding为0,否则会由于padding和margin默认不为0的缘故导致出现滚动条。

测试代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  
<title> new document </title>
  
<meta name="generator" content="editplus" />
  
<meta name="author" content="" />
  
<meta name="keywords" content="" />
  
<meta name="description" content="" />
  
<script type="text/javascript">
  
<!--
  
function resize(obj){
  
var ifrm=obj.contentWindow.document.body;
  ifrm.style.cssText
="margin:0px;padding:0px;overflow:hidden";
  
var div=document.createElement("img");
  div.src
=obj.src;
  obj.height
=div.height;
  obj.width
=div.width;
  }
  
//-->
  </script>
</head>

<body>
<input type="button" value="test" onclick="document.getElementById('a').style.display=''">
  
<iframe src="1.jpg" id="a" style="display:none" scrolling="auto" onload="resize(this)"></iframe>
</body>
</html>

posted on 2007-10-12 16:21 Yemoo'S JS Blog 阅读(1932) 评论(1)  编辑 收藏 引用 所属分类: javascript技巧总结

评论

# re: iframe src为图片时的高度自适应 2014-01-16 09:35 12
123  回复  更多评论
  

只有注册用户登录后才能发表评论。