Javascript/Jquery: Auto adjust height of iframe (h

2019-09-02 19:12发布

问题:

I have the following code that makes the iframe taller once text exceeds iframe visible height; however, when text is removed, the iframe remains just as tall. How do I modify this code (or if there is a different code) that will adjust the iframe to be JUST the right height. I need this to be in a function so that on keyup I can run the function.

function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}

回答1:

Disclaimer: Not sure if below solution is the best one.

You can reset iframe to your standard size and then resize it using your method.

Example:

If the standard size of your iframe is 300px by 300px

function autoResize(id){
   //Reset iframe size
   document.getElementById(id).height= "300px";
   document.getElementById(id).width= "300px";

   //Your method continues
   var newheight;
   var newwidth;

   if(document.getElementById){
       newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
       newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
   }

   document.getElementById(id).height= (newheight) + "px";
   document.getElementById(id).width= (newwidth) + "px";
}

Hope this helps