简体   繁体   English

如何获取iframe的高度和宽度

[英]How to get the height and width of an iframe

How to get the height and width of an iframe , executing a script from outside the iframe ?如何获得的高度和宽度iframe ,从外面执行脚本iframe

I want to find its dimensions.我想找到它的尺寸。

Javascript solutions welcomed.欢迎 Javascript 解决方案。

Using pure javascript:使用纯 javascript:

document.getElementsByTagName('iframe')[0].getAttribute('width');
document.getElementsByTagName('iframe')[0].getAttribute('height');

Using JQuery: 使用JQuery:

$('iframe').height();
$('iframe').width();

Edit Elaborating on the quick and dirty answer above. 编辑上面的快速而肮脏的答案的详尽阐述。 .height() and .width() will give you the element's height and width without the padding, border or margin. .height().width()将为您提供元素的高度和宽度,而无需填充,边框或边距。

If you want to include the padding and the border you will need to use .innerHeight() and .innerWidth() . 如果要包括填充和边框,则需要使用.innerHeight().innerWidth() Example below: 下面的例子:

$('iframe').innerHeight();
$('iframe').innerWidth();

If you want to include the padding and the border AND the margin you will need to use .outerHeight() and .outerWidth() . 如果要包括填充,边框和边距,则需要使用.outerHeight().outerWidth() Example below: 下面的例子:

$('iframe').outerHeight();
$('iframe').outerWidth();

Links to the methods above: 链接到上述方法:
https://api.jquery.com/height/ https://api.jquery.com/height/
https://api.jquery.com/innerHeight/ https://api.jquery.com/innerHeight/
https://api.jquery.com/outerHeight/ https://api.jquery.com/outerHeight/
https://api.jquery.com/width/ https://api.jquery.com/width/
https://api.jquery.com/innerWidth/ https://api.jquery.com/innerWidth/
https://api.jquery.com/outerWidth/ https://api.jquery.com/outerWidth/

getBoundingClientRect returns an object with the following keys: left , top , right , bottom , x , y , width und height . getBoundingClientRect返回具有以下键的对象: lefttoprightbottomxywidthheight

 const { width, height } = document.querySelector("iframe").getBoundingClientRect(); console.log(width, height);
 <p>Example for iframe dimensions</p> <iframe src="https://www.example.com"></iframe>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM