Javascript 从 iframe 内部检测 <iframe> 的高度和宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7808729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect <iframe> height and width from inside the iframe
提问by CLiown
I doubt this is actually possible but Im prepared to be corrected.
我怀疑这实际上是可能的,但我准备纠正。
What I need is to be able to detect the width and height of an iframe from within the iframe, so if the iframe src
is iframeContent.html
I need to be able to surface the values on this page.
我需要的是能够从 iframe 中检测 iframe 的宽度和高度,因此如果 iframesrc
是iframeContent.html
我需要能够显示此页面上的值。
I have no control over the page that hosts the iframe only the contents of the iframe.
我无法控制承载 iframe 的页面,只能控制 iframe 的内容。
Is this possible?
这可能吗?
采纳答案by Teneff
You can always get the web page dimensions, no matter if the page is loaded inside an iframe
or a new window it always works the same way. This is a function I've found used to get window
dimensions, you can also use it to get an <iframe>
dimensions.
您始终可以获取网页尺寸,无论页面是在iframe
窗口内还是在新窗口中加载,它始终以相同的方式工作。这是我发现用于获取window
尺寸的函数,您也可以使用它来获取<iframe>
尺寸。
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
- source(thanks Andy E for adding the link)
- jsFiddle example
- 来源(感谢 Andy E 添加链接)
- jsFiddle 示例