iframe宽高自适应

iframe
	|--index
		|-index.html
	|--iframe
		|--iframe.html
		|--iframe.js
<!-- index/index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>iframe宽高自适应 - 方案1</title>
</head>

<body>
  <iframe id="iframe1" src="../iframe/iframe.html" width="300" height="200">
  </iframe>
</body>

</html>
<!-- iframe/iframe.html -->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>iframe</title>
  <script src="iframe.js"></script>
</head>

<body>
  <button onclick="stop()">暂停</button>
</body>

</html>
// iframe/iframe.js
let interval

window.onload = function () {
  if (!interval) {
    interval = setInterval(appendChild, 1000)
  }
}

function appendChild(i) {
  let e = document.createElement('div')
  e.innerHTML = `测试`
  document.body.appendChild(e)
  setIframeHeight(window.parent.document.getElementById('iframe1'))
}

function stop() {
  clearInterval(interval)
}

function setIframeHeight(iframe) {
  // console.log(iframe)
  if (iframe) {
    var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow
    if (iframeWin.document.body) {
      iframe.height =
        iframeWin.document.documentElement.scrollHeight ||
        iframeWin.document.body.scrollHeight
    }
  }
}

版权声明:本文为pfdvnah原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。