簡體   English   中英

在Google Chrome瀏覽器中獲取iframe內容的高度

[英]Get iframe content height in Google Chrome

誰能幫我在Google Chrome上執行此代碼? 它在IE上完美運行。

謝謝。

<!doctype html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
  <script>
    function calcIframeSize() {
      var altura = $("body", $("#frameExtraFields").contents()).height();
      $("#frameExtraFields").height(altura);
    }
    $(document).ready(function() {
      $("#frameExtraFields").ready( function() {
        calcIframeSize();
      });
    });
  </script>
</head>
<body>

<iframe src="frame.html" width="80%" height="600" id="frameExtraFields"></iframe>

</body>
</html>

考慮到您的iframe在相同的域上加載了src ,應執行以下操作:

<script>
    $(document).ready(function() {
        $('#frameExtraFields').load(function() {
            $(this).height($(this).contents().height());
        });
    });
</script>

<iframe src="/user/login/" width="80%" height="auto" id="frameExtraFields"></iframe>

請注意,我刪除了在iframe元素上設置的固定高度,並將其設置為auto

看到這個小提琴

解:

對於所有專門用於chrome的瀏覽器,我都會使用以下代碼:

.offsetHeight返回相比鍍鉻相同的值.scrollHeight在瀏覽器中的其余部分。

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

if (document.getElementById) {
    newheight = isChrome 
    ? document.getElementById(id).contentWindow.document.body.offsetHeight 
    : document.getElementById(id).contentWindow.document.body.scrollHeight;
}

調整iframe高度大小的完整功能:

function autoResize(id) //id = iframe-id
{
    var newheight = 500;
    var newwidth;

    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if (document.getElementById) {
        newheight = isChrome ? document.getElementById(id).contentWindow.document.body.offsetHeight : document.getElementById(id).contentWindow.document.body.scrollHeight;

        newheightVisible = newheight + 30; //Don't ask me why this, i am also wondering but it works
    }

    if (newheight != lastheight) {
        jQuery("#" + id).css('height', newheightVisible);
        lastheight = newheightVisible;
    }
}

暫無
暫無

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

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