用jQuery控制iframe高度

Sar*_*nan 20 html iframe jquery

我使用jQuery来控制iframe的高度.

jQuery("iframe",top.document).contents().height();  
Run Code Online (Sandbox Code Playgroud)

这在iframe的高度增加时有效.当高度降低时,它不起作用.它仅返回旧值.为什么会这样?

小智 30

我使用以下,它完美地工作......

$("#frameId").height($("#frameId").contents().find("html").height());
Run Code Online (Sandbox Code Playgroud)

当然只是在它被调用时(没有"自动调整大小")......但它的工作量随着减少而增加

  • 我不认为这适用于**跨域**.如果您有解决方案,请帮忙. (5认同)

Jos*_*lio 5

它适用于我如果我设置并检索它而不使用.contents().请参阅下面的示例.

function changeFrameHeight(newHeight){
  jQuery("iframe",top.document).height(newHeight);
  alert("iframe height=" + jQuery("iframe",top.document).height());
}
Run Code Online (Sandbox Code Playgroud)

编辑:如果我理解正确,你试图通过调用增量去除滚动条,并通过调用减量返回到原始高度.

在不同浏览器上进行多项测试之后.这是在FF,IE,Chrome,Safari和Opera中运行的代码.

//first declare a variable to store the original IFrame height.
var originalHeight = $("iframe",top.document).height();
Run Code Online (Sandbox Code Playgroud)

更改heightIncrement函数以使用以下内容:

heightIncrement:function(){
 var heightDiv = jQuery("iframe",top.document).contents().find('body').attr('scrollHeight'); 
 jQuery("iframe",top.document).css({height:heightDiv});
}
Run Code Online (Sandbox Code Playgroud)

更改heightDecrement函数以使用以下内容:

heightDecrement:function(){
 jQuery("iframe",top.document).css({height:originalHeight});
}
Run Code Online (Sandbox Code Playgroud)