简体   繁体   中英

Dynamic iframe height

I have a problem. I'm working on a template which is composed by a central div and an iframe inside it. The div should resize dynamically depending on the content of the iframe. I tried other solutions found here, without results. I'm using the following HTML code:

<div id="site_content" style="position:relative; width:445px; height:500px;">

    <iframe id="mainframe" name="mainframe" onload="parent.adjustIFrameHeight();" FRAMEBORDER="0" scrolling="no" style="overflow:hidden; border:none;" src="http://www.letsapp.it/alecianetti/" width="445" height="600"></iframe>

</div>

I would like the div (#site_content) resize dynamically on iframe content change. I tried this function but I'm not very expert in using js and similar (I'm studying them now;)) so I don't know if it's useful or correct

onload="parent.adjustIFrameHeight();"

To give you an idea of the result, I link you a demo site of ThemeForest Wave CV which is the template I'm replicating.

Can anyone help me?

Just tried it out!

    <script type="text/javascript">
        function setIframeHeight(iframeName) {
          //var iframeWin = window.frames[iframeName];
          var iframeEl = document.getElementById? document.getElementById(iframeName): document.all? document.all[iframeName]: null;
          if (iframeEl) {
          iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous
          //var docHt = getDocHeight(iframeWin.document);
          // need to add to height to be sure it will all show
          var h = alertSize();
          var new_h = (h-148);
          iframeEl.style.height = new_h + "px";
          //alertSize();
          }
        }

        function alertSize() {
          var myHeight = 0;
          if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myHeight = window.innerHeight;
          } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            //IE 6+ in 'standards compliant mode'
            myHeight = document.documentElement.clientHeight;
          } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            //IE 4 compatible
            myHeight = document.body.clientHeight;
          }
          //window.alert( 'Height = ' + myHeight );
          return myHeight;
        }
    </script>

</head>
<body onload="setIframeHeight('ifr');">
<center>
    <iframe id="ifr" src="yourdomain!" onload="parent.adjustIFrameHeight();" width="850px" scrolling="no" ></iframe>
</center>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM