为什么iframe的CSS边框会闪烁,如何解决?

gma*_*man 8 html css safari iframe google-chrome

我有一个使用CSS的iframe边框。调整页面大小后,边框有时会在Chrome中消失,而在Safari中会更改大小(在Firefox中可以)

在此处输入图片说明

有已知的解决方法吗?

const html = `
<style>
body { 
  background: #DDD;
}
</style>
<body>
  <div>hello iframe</div>
</body>
`;

const blob = new Blob([html], {type: 'text/html'});
document.querySelector("iframe").src = URL.createObjectURL(blob);
Run Code Online (Sandbox Code Playgroud)
div {
  max-width: 90%;
  margin: 0 auto;
}
iframe {
  display: block;
  border: 1px solid black;
  width: 100%;
  background: red;
}
Run Code Online (Sandbox Code Playgroud)
<p>Size the window and watch the right border</p>
<!-- src set from JavaScript because offsite iframes are often banned -->
<div>
  <iframe></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)

使用其他元素没有相同的问题

div {
  max-width: 90%;
  margin: 1em auto;
}
span, canvas {
  display: block;
  border: 1px solid black;
  width: 100%;
  height: 60px;
  background: #eee;
}
Run Code Online (Sandbox Code Playgroud)
<p>no issue with other elements</p>
<div>
  <span></span>
</div>
<div>
  <canvas></canvas>
</div>
Run Code Online (Sandbox Code Playgroud)

请注意,这似乎与iframe中的背景色有关。如果我删除了背景色,Chrome中的问题就解决了(尽管不是Safari)

const html = `
<body>
  <div>hello iframe</div>
</body>
`;

const blob = new Blob([html], {type: 'text/html'});
document.querySelector("iframe").src = URL.createObjectURL(blob);
Run Code Online (Sandbox Code Playgroud)
div {
  max-width: 90%;
  margin: 0 auto;
}
iframe {
  display: block;
  border: 1px solid black;
  width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<p>Size the window and watch the right border</p>
<!-- src set from JavaScript because offsite iframes are often banned -->
<div>
  <iframe></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)

iic*_*ain 1

添加一个包装 div 和overflow: hidden;适合box-sizing: border-box;我。

const html = `
<style>
body { 
  background: #eee;
}
</style>
<body>
  <div>hello iframe</div>
</body>
`;

const blob = new Blob([html], {type: 'text/html'});
document.querySelector("iframe").src = URL.createObjectURL(blob);
Run Code Online (Sandbox Code Playgroud)
div {
  max-width: 90%;
  margin: 0 auto;
}
.iframe-wrapper {
  border: 1px solid black;
  box-sizing: border-box;
  width: 100%;
  overflow: hidden;
}
iframe {
  display: block;
  width: 100%;
  border: none;
}
Run Code Online (Sandbox Code Playgroud)
<p>Size the window and watch the right border</p>
<!-- src set from JavaScript because offsite iframes are often banned -->
<div>
  <div class="iframe-wrapper">
     <iframe></iframe>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)