Use jQuery to solve the iframe adaptive height problem without judging the browser height

  • 2020-05-05 10:56:56
  • OfStack

Here are two super easy ways to determine a browser's height and width without writing anything.

Choose one of the two methods below. One is on the same page as iframe and one is on test.html.

Be careful not to misplace it.
In the code for iframe, note that ID,

cannot be found without ID


<iframe src="test.html" id="main" width="700" height="300" frameborder="0" scrolling="auto"></iframe>

Method 1:


// Note: the following code is placed in and iframe Same page call
$("#main").load(function(){
var mainheight = $(this).contents().find("body").height()+30;
$(this).height(mainheight);
});

Method 2:


// Note: the following code is placed test.html call
$(window.parent.document).find("#main").load(function(){
var main = $(window.parent.document).find("#main");
var thisheight = $(document).height()+30;
main.height(thisheight);
});

We need to use iframe in the process of doing the project, but iframe has a default height, and the content that exceeds the default height will be hidden, while the content that is less than the default height will regard the default height as the height of the content. In the process of looking for the answer, we found how to control the iframe height and adapt

The iframe adaptive height itself is a simple way to recalculate the height after the page loads.

The code is as follows:


// Public method: set iframe To ensure full display of data
//function SetPageHeight() {
//    var iframe = getUrlParam('ifname');
//    var myiframe = window.parent.document.getElementById(iframe);
//     iframeLoaded(myiframe);
//}
var iframeLoaded = function (iframe) {
    if (iframe.src.length > 0) {
        if (!iframe.readyState || iframe.readyState == "complete") {
            var bHeight =
            iframe.contentWindow.document.body.scrollHeight;
            var dHeight =
            iframe.contentWindow.document.documentElement.scrollHeight;
            var height = Math.max(bHeight, dHeight);
            iframe.height = height;
        }
    }
}
// Reset when paging iframe highly ; Revised: iframe.name = iframe.id
var reSetIframeHeight = function()
{
    try {
        var oIframe = parent.document.getElementById(window.name);
        oIframe.height = 100;
        iframeLoaded(oIframe);
    }
    catch (err)
    {
        try {
         parent.document.getElementById(window.name).height = 1000;
          } catch (err2) { }
    }
}

Call reSetIframeHeight (); The method is ok.


Related articles: