iframe里面的高度和外面的不一致,如何破

4,149 阅读2分钟

让你明明白白学知识,有代码,有讲解,抄的走,学的会!

我们在一些应用场景中使用iframe的时候,可能会遇到,iframe不能撑满指定区域的面积,始终就是欠缺那么一点

先上图,再说事

这是再简单不过的布局了

主页面 index.html

<style>
    * {
      color: #fff;
      margin: 0;
    }
    .top-head {
      width: 100%;
      height: 88px;
      background-color: red;
    }
    .main {
      display: flex;
      height: calc(100vh - 88px);
    }
    .nav-left {
      width: 120px;
      height: calc(100vh -88px);
      background-color: green;
    }
    .right-content {
      flex: 1;
      height: calc(100vh - 88px);
      background-color: pink;
    }
    .right-content .content {
      /* 强烈建议手动指定一下,避免1px间隔,审查元素都查询不出来 */
      display: block;
      width: 100%;
      height: inherit;
    }
  </style>
<body>
    <!--我们理解的头部区域-->
    <div class="top-head">xxx一些内容</div>

    <div class="main">
        <div class="nav-left">左边的内容</div>
        <div class="right-content">
          <iframe src="./content.html" class="content" scrolling="no" frameborder="0" marginheight="0" marginwidth="0" width="100%" style="vertical-align:bottom"></iframe>
        </div>
    </div>
</body>

iframe中的区域 content.html

<style>
body {
  width: 100%;
  height: calc(100vh - 88px);
}

.fill-body {
  width: 100%;
  height: inherit;
  background-color: aqua;
}
</style>
<body>
  <div class="fill-body">
    我是iframe中的内容
  </div>
</body>

我们先通过审查元素,查看一下 .right-content 这个包裹在iframe外层的div高度,宽度我们不关心

div.right-content 高度 634.4 再审查iframe 高度 也是 634.4 心里想,妥妥的,没毛病

再看iframe里面的body和html高度 546.4

这差距去哪里了? 好,现在说怎么解决

解决

1、先指定好 iframe元素的display: block; 因为iframe默认会有一些样式, 莫名奇妙的会多出1px问题,导致白边,手动指定一下

2、指定iframe外层容器的宽度,高度,达到我们想要的效果,这个没啥问题吧,老铁!

3、iframe上面一些边框之类的设置一下

<iframe src="./content.html" class="content" scrolling="no" frameborder="0" marginheight="0" marginwidth="0" width="100%"  style="vertical-align:bottom"></iframe>

4、设置iframe里面的高度, 通过js去获取.right-content或者iframe元素的高度。然后设置iframe里面body的高度,就可以

原生js实现 content.html中加入下面内容

let height = parent.window.document.querySelector(".right-content").clientHeight

document.querySelector("body").style.height = height + "px"

jquery实现

let height = $(".right-content",parent.document).height()

$("body").height(height)

最终效果

我们index.html中.nav-right 背景指定的是 background-color: green;

现在只看到了 iframe里面body的颜色 aqua 就说明成功了,100% 覆盖住了

可能你会看到网上形形色色的解决方案,什么 * {padding: 0; margin: 0} 之类的, 这些憨憨自己都不测试的

求学,要脚踏实地,自己实践得出真知!