iframe高度自适应
iframe现在用的不多了,不过很多项目中还是需要用的到的,看到就转载过来了,再学习下。
高度自适应代码代码如下:
<iframe src="test 2.html" width=“100%” height="600" id="iframe1" onload="iFrameHeight('iframe1')" name="iframe1"></iframe>
<iframe src="test 2.html" id="iframe2" onload="iFrameHeight('iframe2')" name="iframe2"></iframe>
<iframe src="test 2.html" id="iframe3" onload="iFrameHeight('iframe3')" name="iframe3"></iframe>
<iframe src="test 2.html" id="iframe4" onload="iFrameHeight('iframe4')" name="iframe4"></iframe>
</body>
<script>
console.log(document.getElementById("iframe3").contentWindow);
function iFrameHeight(id) {
var ifm= document.getElementById(id);
var subWeb = document.frames ? document.frames[id].document :ifm.contentDocument;
if(ifm != null && subWeb != null) {
ifm.height = subWeb.body.scrollHeight;
}
}
</script>
关于test 2.html就是你要预览的pdf页面,可以很长!
注意事项:
1、上述代码必须在localhost等服务器环境下面预览
2、test 2.html也就是iframe的src必须是同域下面
代码解释
document.getElementById("iframe3").contentWindow
可以获取iframe的window对象。
谷歌浏览器可以通过
document.frames[id].document 获取document对象
Firefox 支持, ie8 以上的ie可以通过
document.getElementById(id).contentDocument 来获取document对象。
其他解释
其实操作iframe的方法还有很多!例如jquery有个contents()方法,可以查找iframe中的某个id或者某段内容。
例如:
$("#iframe2").contents().find("someID").html() 或者 $("#mainiframe").contains().find("someID").text()
iframe2中包含某个ID。
也可以js和jquery混着用!例如:
$(window.frames["iframe1"].document).find("input[@type='radio']").attr("checked","true");
原文:http://www.haorooms.com/post/ifame_height_zishiying

浙公网安备 33010602011771号