jq如何监听iframe内的body高度
要监听dom 第一个就应该想到MutationObserver
以下是效果图
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>child</title>
<style>
body{
border: solid 10px red;
}
</style>
</head>
<body>
<script>
const body = document.body;
// 监听
const observer = new MutationObserver(mutationsList => {
// 得到当前的高度
const currentHeight = window.getComputedStyle(body,null).height;
// 向父窗口发数据
top.postMessage(currentHeight,"*");
});
observer.observe(body, {
attributes: true,
childList: true,
subtree: true,
});
// 定时随机变化body高度
const random = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
setInterval(() => {
body.setAttribute("style", `height:${random(100, 500)}px`);
}, 2000);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>parent</title>
<style>
#fm {
height: 600px;
}
</style>
</head>
<body>
<p id="text"></p>
<iframe id="fm" src="child.html" frameborder="0"></iframe>
<script>
const p = document.querySelector("#text");
// 监听发来的数据
window.addEventListener("message", function(e) {
p.innerHTML = `当前child高度为${e.data}`;
});
</script>
</body>
</html>
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
$(document.getElementById("iframe的name").contentWindow).find('body').height()