如何使用JavaScript将全屏iframe的高度设置为100%
给定一个包含<iframe>
元素的HTML文档,任务是使用JavaScript将< iframe>元素的高度更改为100%。有两种方法可以更改iframe的高度,如下所述:
方法1
此方法使用iframe的id属性和height属性来更改<iframe>
元素的高度。 JavaScript代码写在<script>
标签中。
<html>
<head>
<title>
How to change the height of an
iframe to 100% with JavaScript?
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
How to change the height of a
<iframe id="iframe" width="100%" height="40%"
src="https://www.youtube.com/embed/hjGD08xfg9c"
frameborder="0" allowfullscreen>
</iframe> to 100% with JavaScript?
</h3>
<br><br>
<button onclick="changeHeight()">
Click to change
</button>
<script>
// JavaScript code to change the
// height to 100% of <iframe>
function changeHeight() {
var x = document.getElementById('iframe');
x.style.height = "100%";
}
</script>
</body>
</html>
输出:
- 在点击按钮之前:
- 在点击按钮之后:
方法2
该方法使用iframe的id属性和window.innerHeight属性来改变元素的高度。JavaScript代码写在<script>
标签中。
<html>
<head>
<title>
How to change the height of an
iframe to 100% with JavaScript?
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
How to change the height of a
<iframe id="iframe" width="100%" src=
"https://www.youtube.com/embed/hjGD08xfg9c"
frameborder="0" ></iframe>
to 100% with JavaScript?
</h3>
<br><br>
<button onclick="changeHeight()">
Click to change
</button>
<script>
// JavaScript code to change the
// height to 100% of <iframe>
function changeHeight() {
var x = document.getElementById('iframe');
x.style.height = window.innerHeight;
}
</script>
</body>
</html>
输出:
- 点击按钮前:
- 点击按钮后: