js获取iframe高度
获取 iframe 的高度可以通过访问 iframe 的 contentDocument 对象和 scrollHeight 属性来实现。 具体方法如下:
12var iframe = document.getElementById('myiframe');var iframeHeight = iframe.contentDocument.documentElement.scrollHeight;
这里的 myiframe 是 iframe 的 id, contentDocument 是 iframe 的文档对象, scrollHeight 是文档的滚动高度。如果你要在 iframe 中嵌入一个页面并且想要自适应 iframe 高度,可以使用以下代码:
12345678function 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; } }}
这个函数将根据 iframe 的内容自动调整 iframe 的高度。如果您需要在 iframe 加载完成后自动调整高度,可以使用以下代码:
1234var iframe = document.getElementById('myiframe');iframe.onload = function() { setIframeHeight(iframe);};
请注意,在不同的浏览器和环境中,获取 iframe 高度的方法可能会有所不同。在某些情况下,还需要考虑跨域访问的问题。
转载 js获取iframe高度
赏
谢谢你请我吃糖果
微信