[英]iframe dynamic height width change based on inner content
我的iframe內容如下
<iframe frameborder="no" src="http:localhost/com" id="iframe">
<div style="height:850px;width:700px;">div text </div>
</iframe>
這顯示了帶hori的iframe。 和垂直滾動,但內部內容的高度不為850px。
如何根據內部內容高度n寬度動態更改iframe高度。 我在內容內使用jQuery。
它的跨域js小部件,因此以下大多數答案引發了拋出權限被拒絕的錯誤
納西什·坦克斯
var newHeight = $("iframe[id='iframeAutenticador']").contents().find("html").height();
$("iframe[id='iframeAutenticador']").height(newHeight);
用這個。
虛無
如果您使用的是jquery,則可以輕松地找到(並設置)任何div的高度(在您的域中-不在外部內容上),如下所示:
// get the height - in case we want to factor it into the equation below!!
var myDivHeight = $('iframe').css('height');
// set the height
var docHeight = $(document).css('height');
$('iframe').css('height', docHeight);
希望這可以幫助 ...
您應該創建一個函數來測量內容的高度,並設置IFrame的高度,然后在加載內容時調用resize函數。
<SCRIPT LANGUAGE="JavaScript">
function resizeIframeToFitContent(iframe) {
// This function resizes an IFrame object
// to fit its content.
// The IFrame tag must have a unique ID attribute.
iframe.height = document.frames[iframe.id]
.document.body.scrollHeight;
}
</SCRIPT>
如果兩個頁面的域都相同:
parent.document.getElementById("iframe").style.height = $(document).height()+"px";
您也可以在父頁面中使用jQuery(如果在那里可用)。
我在這里找到了這個: stackoverflow.com/questions/1145850/
並在其上擴展以重新調整寬度...只需將其添加到您的頭部即可:
<script type="text/javascript">
function getDocHeight(doc) {
doc = doc || document;
// stackoverflow.com/questions/1145850/
var body = doc.body, html = doc.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
return height;
}
function getDocWidth(doc) {
doc = doc || document;
// stackoverflow.com/questions/1145850/
var body = doc.body, html = doc.documentElement;
var width = Math.max( body.scrollWidth, body.offsetWidth,
html.clientWidth, html.scrollWidth, html.offsetWidth );
return width;
}
function setIframeSize(id) {
var ifrm = document.getElementById(id);
var doc = ifrm.contentDocument? ifrm.contentDocument:
ifrm.contentWindow.document;
ifrm.style.visibility = 'hidden';
ifrm.style.height = "10px"; // reset to minimal height ...
ifrm.style.width = "10px"; // reset to minimal width ...
// IE opt. for bing/msn needs a bit added or scrollbar appears
ifrm.style.height = getDocHeight( doc ) + 4 + "px";
ifrm.style.width = getDocWidth( doc ) + 4 + "px";
ifrm.style.visibility = 'visible';
}
</script>
然后,確保您在iframe中具有唯一的ID,然后調用SetIframeSize:
<iframe src="source.html" id="uniqueid" onload="setIframeSize(this.id)"></iframe>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.