iframe高度动态自适应,一直是个头疼的问题,今天我们从事件监听这个角度,来实现iframe高度实时更新。
方案一:监听iframe体的点击事件
<iframe src="cascade.jsp" onload="addEvt(this)"></iframe>
function addEvt(ifm){ var addHeight = function(ifmObj){ if(ifmObj){ }else{ return; } var win = ifmObj.contentWindow, doc = win.document,$.each(body.childNodes,function(index,node){/* 迭代所有可见元素高度累加 */
body = doc.body, html = doc.documentElement, height = html.offsetHeight;
var domHeight = node.offsetHeight || 0;
if(index == 0) height = domHeight;
else height += domHeight;
});
$(ifmObj).height(height); } var doc=ifm.contentWindow.document; doc.onclick=function(){ addHeight(ifm); } addHeight(ifm); $(ifm).css({'100%',border:0}).attr("scrolling","no");/*设置无边框和滚动条*/ setTimeout(function(){$(doc).trigger("click");},1000); }
方案二:监听iframe的滚动事件
<iframe class="autoHeight" src="cascade.jsp"></iframe>
$(function(){ bindIfmScroll(); }); function bindIfmScroll(){ var addHeight = function(ifm){ if(ifm){ }else{ return; } var win = ifm.contentWindow, doc = win.document, html = doc.documentElement, body = doc.body; var height = Math.max( //body.scrollHeight, //body.offsetHeight,html.clientHeight, //html.scrollHeight, html.offsetHeight ); $(ifm).height(height); } var ifms = $("iframe.autoHeight"); /*自动检索class为‘autoHeight’的iframe*/
ifms.css({'100%',border:0}).attr("scrolling","no");/*设置无边框和滚动条*/ ifms.each(function(){ var ifmObj = this; $(ifmObj.contentWindow).scroll(function() { addHeight(ifmObj); }); }); }
试验之后,方案一更好些。以上仅供参考,列位如果有更好方案希望能分享出来o(^▽^)o