简体   繁体   English

使用CSS和JavaScript更改iframe宽度

[英]IFrame width change with CSS and JavaScript

I'd like the width of my IFrame to be one of two sizes, depending on the width of the browser window. 我希望IFrame的宽度是两种大小之一,具体取决于浏览器窗口的宽度。 Unfortunately the code below doesn't give the expected results, even on refresh. 不幸的是,即使刷新,下面的代码也无法提供预期的结果。 What am I doing wrong? 我究竟做错了什么?

The HTML is as follows: HTML如下:

<p>A frame example:<br>
    <iframe src="www.google.com">
    </iframe>
</p>

At the beginning, I import a stylesheet that works in all regards except the following: 首先,我导入一个样式表,该样式表在所有方面均适用,但以下各项除外:

iframe
{
<script>
    if (window.innerWidth<800px)
    {
    width="200";
    }
    else
    {
    width="400";
    }
</script>
height="400";
}

Any ideas on what I can improve? 关于我可以改善的任何想法?

You can't use javascript inside css. 您不能在CSS中使用javascript。 Just use media queries to solve the problem 只需使用媒体查询即可解决问题

@media all and (max-width:800px) {
    iframe {
        width: 200px;
    }
}

@media all and (min-width: 801px) {
    iframe {
        width: 400px;
    }
}

Using css media queries is preferable but if you'd like to change the width using JavaScript, you can listen to the onresize window event and change the width inside the event handler. 最好使用CSS媒体查询,但是如果您想使用JavaScript更改宽度,则可以侦听onresize窗口事件并在事件处理程序中更改宽度。

Note that I added an id to the iframe so you can quickly select it in the JavaScript. 请注意,我在iframe中添加了一个id ,因此您可以在JavaScript中快速选择它。

HTML HTML

<iframe id="myIframe" src="www.google.com"></iframe>

JavaScript JavaScript的

(function() {
    var iframe = document.getElementById('myIframe');
    iframe.height = 400;

    window.onresize = resizeIframe;

    function resizeIframe() {
        if (window.innerWidth < 800) {
            iframe.width = 200;
        }
        else {
            iframe.width = 400;
        }
    }
}());

Check out the jsfiddle example 查看jsfiddle示例

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

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