JavaScript 如何将iframe的宽度更改为100%

JavaScript 如何将iframe的宽度更改为100%

在本文中,我们提供了一个包含<iframe> 元素的HTML文档,并且任务是使用JavaScript将<iframe> 元素的宽度更改为100%。有两种方法可以更改iframe的宽度,下面将进行讨论:

方法1: 此方法使用iframe的id属性和宽度属性来更改<iframe> 元素的宽度。JavaScript代码写在<script>标签中。

<!DOCTYPE html> 
<html>  
    
<head>  
    <title>  
        How to change the width of an  
        iframe to 100% with JavaScript?  
    </title>  
</head>  
     
<body>  
    <center> 
        <h1 style="color:green;">  
            GeeksforGeeks   
        </h1>  
        <h3>  
            How to change the width of a <br> 
            to 100% with JavaScript?  
        </h3>  
        <iframe id="iframe" height="100%" width="40%"
            src="https://www.youtube.com/embed/HzeK7g8cD0Y"
            frameborder="0" allowfullscreen>  
        </iframe> 
  
        <br><br>  
        <button onclick="changewidth()">  
            Click to change  
        </button>  
          
        <script>  
  
            // JavaScript code to change the  
            // width to 100% of <iframe>  
            function changewidth() {  
                var x = document.getElementById('iframe');  
                x.style.width = "100%";  
            }  
        </script>  
    </center> 
</body>   
</html>

输出:

JavaScript 如何将iframe的宽度更改为100%

方法2: 该方法使用iframe的id属性和window.innerWidth属性来改变元素的宽度。JavaScript代码写在<script>标签中。

<!DOCTYPE html> 
<html>  
<head>  
    <title>  
        How to change the width of an  
        iframe to 100% with JavaScript?  
    </title>  
</head>  
     
<body>  
    <center> 
        <h1 style="color:green;">  
            GeeksforGeeks   
        </h1>  
        <h3>  
            How to change the width of a <br> 
            to 100% with JavaScript?  
        </h3>  
        <iframe id="iframe" height="100%" width="40%"
            src="https://www.youtube.com/embed/HzeK7g8cD0Y"
            frameborder="0" allowfullscreen>  
        </iframe> 
  
        <br><br>  
        <button onclick="changewidth()">  
            Click to change  
        </button>  
          
        <script>  
            // JavaScript code to change the  
            // width to 100% of <iframe>  
            function changewidth() {  
                var x = document.getElementById('iframe');  
                x.style.width = window.innerWidth;  
            }  
        </script>  
    </center> 
</body>   
</html>

输出:

JavaScript 如何将iframe的宽度更改为100%

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程