iframe父页面和子页面高度自适应

时间:2021-09-12 10:22:08

父页HTML:

<iframe  id="mainframe" name="mainframe"  style="width:100%;" marginheight="0" marginwidth="0" onLoad="iFrameHeight()"  scrolling="auto" frameborder="0"   src="Index.aspx"></iframe>

父页JS:

<script src="../Scripts/js/jquery-2.1.1.min.js"></script>

<script>
        function iFrameHeight() {
            var ifm = document.getElementById("mainframe");
            var subWeb = document.frames ? document.frames["mainframe"].document : ifm.contentDocument;
            if (ifm != null && subWeb != null) {
                ifm.height = document.body.offsetHeight;
                ifm.width = subWeb.body.scrollWidth;
            }
        }
    </script>

子页JS

<script src="../Scripts/js/jquery-2.1.1.min.js"></script>

<script>

$(window.parent.document).find("#mainframe").load(function () {
      var ifm = window.parent.document.getElementById("mainframe");
      var subWeb = window.parent.document.frames ? window.parent.document.frames["mainframe"].document : ifm.contentDocument;
      if (ifm != null && subWeb != null) {
           ifm.height = subWeb.body.offsetHeight + 20;               //预留出灵活高度20px
          ifm.width = subWeb.body.scrollWidth;
      }
    
  });

</script>