根据内容调整iframe大小
iframe HTML元素经常用于插入来自另一个源的内容。需要调整大小的内容通过使用div标签间接完成。诀窍是使用div标签初始化并在iframe标签内部封闭。现在为iframe提供CSS。
注意: 要打开源站点以调整其内容,源站点必须在同一个目录中列出。
示例1: 下面是使用内部CSS调整内容的HTML代码实现:
内部CSS:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: LIGHTGREY;
}
#target {
width: 300px;
height: 200px;
overflow-y: auto;
overflow-x: auto;
resize: both;
position: relative;
z-index: 2;
}
iframe {
width: 100%;
height: 100%;
border: none;
}
</style>
</head>
<body>
<div id="target">
<iframe src="/tryit.php"></iframe>
</div>
</body>
</html>
输出:
在这里,我们使用了内部样式表来将显示区域的尺寸固定为像素宽度和高度。CSS的overflow属性控制了内容是否超出了区域。
示例2: 下面是使用Javascript来调整内容大小的HTML代码的实现:我们将使用JavaScript的contentWindow属性自动根据内容调整iFrame的高度,不会出现滚动条。
- 我们在脚本标记内选择iFrame:
let iframe = document.getElementById(“myIframe”);
-
我们通过以下方式调整iFrame的高度:
iframe.onload = function(){}
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 50%;
}
</style>
</head>
<body>
<iframe src="/tryit.php" id="target">
</iframe>
<script>
let div = document.getElementById("target");
div.onload = function() {
div.style.height =
div.contentWindow.document.body.scrollHeight + 'px';
}
</script>
</body>
</html>
输出: