iframe
|--index
|-index.html
|--iframe
|--iframe.html
|--iframe.js
<!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>
<!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>
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) {
if (iframe) {
var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow
if (iframeWin.document.body) {
iframe.height =
iframeWin.document.documentElement.scrollHeight ||
iframeWin.document.body.scrollHeight
}
}
}