猿问

如何监听iframe中内容高度变化,当iframe中内容高度变化时,改变iframe的高度,即不让

在第一次加载页面时,在父页面调用iframe.onload事件来改变iframe的高度,使得iframe高度自适应

但是当iframe中内容变高时,页面就会出现滚动条,我如何监听页面高度的变化,使得页面变高的时候改变iframe的高度


慕标5832272
浏览 2839回答 1
1回答

Qyouu

你可以多加一个绝对定位宽度为0高度100%的iframe在body里面,然后监听这个iframe的resize事件,当文档的高度变化,就会触发这个事件<html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; body {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; position: relative;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ref {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; position:absolute;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; top: 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; left: 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height:100%;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width:0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; border: none;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; background-color: transparent;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; </style>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>hello world</p>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <!--这是用来监听文档高度变化的iframe-->&nbsp; &nbsp; &nbsp; &nbsp; <iframe class="ref"></iframe>&nbsp; &nbsp; &nbsp; &nbsp; <!--这是正常显示内容的iframe&nbsp; -->&nbsp; &nbsp; &nbsp; &nbsp; <iframe src="xxx"></iframe>&nbsp; &nbsp; &nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var iframeWindow = document.querySelector('.ref').contentWindow;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; iframeWindow.onresize = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('doc height changed');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //在这里改变正常显示内容的iframe的高度&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; </script>&nbsp; &nbsp; </body></html>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答