您的位置:首页 > 其它

iframe自适应高度加载脚本,解决不能使用onload事件问题(兼容)

2014-08-19 14:58 891 查看
这几天公司给客户做了一个页面(使用iframe),客户提出不同用户进入显示不同的内容,接着iframe高度问题就来了,设置高度100%完全没有用。然后在网上各种收集解决办法,一开始网上的方法还真的有作用,但是实际应用发现在iframe框架中有一个模块加载很慢导致页面一开始就显示出来一小部分,还有就是代码不兼容谷歌浏览器,经过两天的各种虐心总算是解决了问题,特意来给大家分享一下。

第一步:父页面index.jsp和子页面sub.jsp,首先两个页面中都要加入<script type="text/javascript" src="js/jquery.min.js"></script>文件,因为需要使用jquery。

第二步:
index.jsp中代码:

<script type="text/javascript">
var ua = navigator.userAgent.toLowerCase(),
UA = ua.match(/(opera|ie|trident|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]|rv[\s?]([\w\d\.]+)|$)/)
|| [null, 'unknown', 0],
mode = (UA[1] == 'ie' || UA[1] == 'trident') && document.documentMode;
var Browser = this.Browser = {
extend: Function.prototype.extend,
name: (UA[1] == 'version') ? UA[3] : (UA[1] == 'trident' ? "ie" : UA[1]),
version: mode || parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2])
};
Browser[Browser.name] = true;
Browser[Browser.name + parseInt(Browser.version, 10)] = true;

function checkFrame() {
//自适应高度方法
//检查iframe是否存在
if($("#content").contents().find("body").height()){
var iframeHeight = $("#content").contents().find("body").height();
$("#content").height(iframeHeight);
if(Browser.chrome){
//判断谷歌浏览器
var mainheight = $(this).contents().find("#div_test").height()+30;

$(this).height(mainheight);
}
}else{
setTimeout("checkFrame()", 200);
}
}
//可以在onload事件之前加载,checkFrame方法可以循环去查找是否完成iframe的加载,加载成功就可以赋值高度,可以在onload事件不能使用的时候解决问题。
$(document).ready(function(){

checkFrame();
});
</script>
页面中的iframe代码:
<iframe id="content" name="content" height="100%" width="100%" src="test.html"
marginwidth="1" marginheight="0" scrolling="no" border="0" frameborder="0" allowTransparency="true"></iframe>

第三步:
sub.jsp中代码:

<script type="text/javascript">
$(window.parent.document).find("#content").ready(function(){
//谷歌浏览器所要使用的代码
var main = $(window.parent.document).find("#content");
var mainheight = $(document).height()+30;
main.height(mainheight);
});
</script>
子页面中获取body高度在不同浏览器不一样,所以要在最外层使用div,然后获取div的高度。
<div class="main_1000" id="div_test">
内容展示部分
</div>

代码兼容性很好,或许没个人遇到问题不同,部分代码通用,大家可以借用部分内容。主要针对的就是不能使用onload事件的时候,还需要加载iframe的高度,还需要兼容IE、火狐、谷歌等浏览器问题。子页面代码在静态页面中脚本会报错,要在程序中使用正常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: