Javascript/Jquery: Auto adjust height of iframe (how to make iframe smaller when needed)

杀马特。学长 韩版系。学妹 提交于 2019-12-25 02:38:09

问题


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



来源:https://stackoverflow.com/questions/21202935/javascript-jquery-auto-adjust-height-of-iframe-how-to-make-iframe-smaller-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!