Control iframe height with jQuery

2019-01-21 17:37发布

I am using jQuery to control the height of an iframe.

jQuery("iframe",top.document).contents().height();  

This works when the height of the iframe increases. When the height decreases it does not work. It returns the old value only. Why is this happening?

9条回答
Fickle 薄情
2楼-- · 2019-01-21 17:57

i use the following and it works perfectly...

$("#frameId").height($("#frameId").contents().find("html").height());

of course just when it's called (no "autoresize")... but it works increasing as decreasing

查看更多
在下西门庆
3楼-- · 2019-01-21 17:59

At the time of loading I call this function

heightIncrement:function(){     
           if($.browser.mozilla)
           { 
             var heightDiv   = jQuery("iframe",top.document).contents().attr("height")+"px";                    
             jQuery("iframe",top.document).css({height:heightDiv});
           }
           else if($.browser.opera  || $.browser.safari || $.browser.msie)
           {               
             var heightDiv   = jQuery("iframe",top.document).height();                   
             jQuery("iframe",top.document).css({height:heightDiv}); 
           } 
}

if I use without contents() it returns zero.

查看更多
Melony?
4楼-- · 2019-01-21 18:09

This is a simple jQuery that worked for me. Tested in iExplorer, Firefox and Crome:

 $('#my_frame').load(function () {  
      $(this).height($(this).contents().find("html").height()+20);
});

I add 20 pixels just to avoid any scroll bar, but you may try a lower bound.

查看更多
登录 后发表回答