这几天公司给客户做了一个页面(使用iframe),客户提出不同用户进入显示不同的内容,接着iframe高度问题就来了,设置高度100%完全没有用。然后在网上各种收集解决办法,一开始网上的方法还真的有作用,但是实际应用发现在iframe框架中有一个模块加载很慢导致页面一开始就显示出来一小部分,还有就是代码不兼容谷歌浏览器,经过两天的各种虐心总算是解决了问题,特意来给大家分享一下。
<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>
<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>
本文分享了解决iframe高度显示不全的问题,并在不同浏览器中实现良好兼容性的方法,包括使用jQuery进行自适应高度调整,以及针对谷歌浏览器的特定代码优化。
3936

被折叠的 条评论
为什么被折叠?



