当页面引入iframe的时候,经常的出现滚动条,现在要让iframe自适应高度
<iframe id="workspace" src="" name="workspace" style="overflow-y:auto;" frameborder="0" width="100%" height="100%" scrolling="no"></iframe>
调整代码
function doIframe(){
o = document.getElementsByTagName('iframe');
for(i=0;i<o.length;i++){
if (/\bautoHeight\b/.test(o[i].className)){
setHeight(o[i]);
addEvent(o[i],'load', doIframe);
}
}
}
function setHeight(e){
if(e.contentDocument){
e.height = e.contentDocument.body.offsetHeight + 35;
} else {
e.height = e.contentWindow.document.body.scrollHeight;
}
}
function addEvent(obj, evType, fn){
if(obj.addEventListener)
{
obj.addEventListener(evType, fn,false);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
}
if (document.getElementById && document.createTextNode){
addEvent(window,'load', doIframe);
}
使用方法
function reinitIframe(){
var iframe = document.getElementById("workspace");
try{
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight);
iframe.height = height;
}catch (ex){
}
}
window.setInterval("reinitIframe()", 200);
iframe随窗口大小变化而变
//iframe随浏览器窗口的大小变动
var pagestyle = function() {
var iframe = $("#workspace");
$("#divRight").width($(window).width()-186);
var w = $(window).width()-iframe.offset().left;
iframe.width(w);
var h = $(window).height()-iframe.offset().top;
if(h>0){
iframe.height(h);
}
}
//注册窗体改变大小事件
$(window).resize(pagestyle);