簡體   English   中英

Javascript一直認為我的IFrame內容和大小為空,但事實並非如此-嘗試調整IFrame的大小以自動插入內容

[英]Javascript always thinking my IFrame content & size are empty, but it isn't - Trying to resize IFrame to injected content automatically

因此,我已經為這個問題苦苦掙扎了幾個小時,所有發現的相關結果都表明我的代碼是正確的,但是顯然這不是,因為它不起作用。

最終,我想做的是jsut調整IFrame高度以匹配其內容(最小100像素)。 注意:Iframe35382-content將通過后端生成,因此這種填充IFrame的方法。

代碼正確地用我想要的數據填充了IFrame並調整其大小,但是由於某些原因,我顯然錯過了內容高度始終返回為150px(我知道這是IFrame的默認高度)以及由內容返回的html的原因().find('html')-用於轉儲IFrame的內容-我出於調試目的吐出的內容始終未定義。

任何幫助或指導都會得到贊賞,可能只需要第二只眼睛就能發現愚蠢的事物__(ツ)_ /

相關代碼如下:

<iframe id="Iframe35382" width="100%" frameborder="0"></iframe>
<script id="Iframe35382-content" type="text/plain">
<html>
<head>
<p>Lengthy html(correctly displaying) shortened for porposes of question</p>
</body>
</html>
</script>
<script type="text/javascript">
function CheckIFrameHeight($frame)
{
  var newHeight = $frame.contents().height();
  alert(newHeight); // DEBUG
  alert($frame.contents().find('html').html()); // DEBUG
  if(!newHeight || isNaN(newHeight))
    newHeight = 100;
  $frame.height(newHeight + 'px');
}
var iframe = document.getElementById('Iframe35382');
iframe.src = 'data:text/html,' + encodeURIComponent($('#Iframe35382-content').text());
CheckIFrameHeight($('#Iframe35382'));
</script>

經過反復試驗,我發現問題出在使用以下代碼將代碼注入框架的方式:

data:text/html, [...]

盡管這是我在Stackoverflow上發現的推薦方法,但它似乎破壞了IFrame起源檢查,使用另一種方法填充IFrame解決了所有問題,即直接寫入IFrame文檔。

// Remove this line
iframe.src = 'data:text/html,' + encodeURIComponent($('#Iframe35382-content').text());

// Replace with these
var iframedoc = iframe.contentDocument;
if(iframedoc)
{
  iframedoc.open();
  iframedoc.writeln($('#Iframe35382-content').text());
  iframedoc.close();
 }

這意味着src atrtibute不再使用-完全返回了content()和height(),從而允許我將IFrame調整為其內容的大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM