手记

postMessage解决iframe自适应高度方法

在localhost环境下
------------------------------父页面-------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<iframe src="child.html" id="ifr"></iframe>
<script type="text/javascript">
window.onload=function(){
var ifr=document.getElementById('ifr');
ifr.contentWindow.postMessage('a','*');

  window.addEventListener('message',function(e){

    var oHeight=e.data;
  },false);
};
</script>
</body>
</html>
-------------------------------子页面------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">

  window.onload=function(){
    window.addEventListener('message',function(e){
    var bodyHeight=document.body.scrollHeight;
       e.source.postMessage(bodyHeight,'http://localhost');
  },false);
  };
</script>

</head>
<body>
一堆东西。。。。自行添加
</body>
</html>

0人推荐
随时随地看视频
慕课网APP