我有一个 iframe 内联 src,例如:
let src = `data:text/html;charset=UTF-8,<html>
<body>
<p>Content</p>
</body>
</html>`
当页面加载时,我正在创建 iframe 并将其添加到页面主体:
let iframe = document.createElement("iframe")
document.querySelector('body').appendChild(iframe)
然后我将 src 设置为 iframe:
iframe.setAttribute('src', src)
如何获取在 iframe 内容中呈现的宽度和高度并设置为 iframe 宽度和高度以及执行此操作的最佳方法是什么(使用 JS 或可能使用 CSS)
最佳答案
我不太确定你想要达到什么目的,所以我只回答问题中关于获取元素的比例并根据另一个元素相应地改变它们的部分。
实现这一目标的最简单方法可能是使用 jQuery
$(function(){
$('#changed').css({'height': $('#whatfrom').height(), 'width': $('#whatfrom').width()});
});
#changed {
height: 50px;
width: 50px;
outline: 1px solid red;
}
#whatfrom {
margin-top: 10px;
height: 150px;
width: 100px;
outline: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="changed">I'll take width and height of the div below me</div>
<div id="whatfrom">Watch.. the element above will take my width and height. What a copycat!</div>
显然将 #changed
和 #whatfrom
div 更改为您需要的任何内容
关于javascript - 获取内联 iframe 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50473488/