我在CSS中使用resize:both;调整iframe的大小。
以编程方式调整iframe大小时,我遇到一个问题。

如果手动调整iframe的大小(即手动拖动),然后通过编程方式(使用JS)调整iframe的大小,则iframe会表现出应有的行为,并且可以调整为任意大小。

但是,如果未手动调整iframe的大小(即手动拖动),然后以编程方式(使用JS)将iframe调整为更大的尺寸,则新尺寸将成为iframe可以拥有的最小尺寸,而iframe只能变得更大。

<div>
        <input type="button" value="Maxmize" onclick="ButtonClick()"></input>
        <input type="button" value="Remove"></input>
        <div>
            <iframe id="theId" class="Resizer" src="">
            </iframe>
        </div>
               </div>

           <style type="text/css">
           .Resizer {resize: both;}
           </style>
           <script>
           function ButtonClick() {
                var iFrame = document.getElementById("theId");
                var iFrameStyleAttr = document.createAttribute('style');
                iFrameStyleAttr.nodeValue = 'width:400px;height:300px;';
                iFrame.setAttributeNode(iFrameStyleAttr);
            }
           </script>


在任何情况下,如何实现减小iframe尺寸的功能?

编辑:我宁愿有一个解决方案,而无需使用JQuery或任何类似的库。

编辑2:我需要一个解决方案才能在Google Chrome 28.0上工作

最佳答案

我相信,默认情况下,iframe不会调整大小。您的解决方案仅对我适用于Chrome 28.0。

使用jQuery和jQuery UI会容易得多。
尝试将这些文件附加到文档的开头部分:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>


然后,您应该为iframe和包含它的div设置初始宽度和高度:

<style type="text/css">
    div#iFrameCon, .Resizer { width: 150px; height: 50px; }
</style>


如您所见,我已经指定了div和最大化按钮id属性,以便使用jQuery选择它们更加容易:

<input id="Maximize" type="button" value="Maxmize"></input>
<input type="button" value="Remove"></input>
<div id="iFrameCon">
    <iframe id="theId" class="Resizer ui-widget-content" src="">
    </iframe>
</div>


现在,您需要的是jQuery UI Resizable插件,该插件可以使用简单的拖动方法来调整iframe及其容器的大小:

<script>
   $(function() {
        $("#iFrameCon").resizable({
            alsoResize: "#theId"
        });
        $("#Maximize").click(function(){
            $("#iFrameCon, #theId").css({ "width": "400px", "height": "300px"});
        });
   });
</script>


希望能帮助到你

编辑

好的,这就是纯JS和CSS方法。我已经对其进行了测试,并且可以在FF v.22和Chrome 28.0中使用。但是,它在所有版本的IE中均失败。

<div>
    <input type="button" value="Maxmize" onclick="ButtonClick()"></input>
    <input type="button" value="Remove"></input>
    <div id="iFrameCon">
        <iframe id="theId" class="Resizer" src="">
        </iframe>
    </div>
 </div>

<style type="text/css">
div#iFrameCon { resize: both; overflow: auto; height: 100px; width: 300px; }
.Resizer { height: 100%; width: 100%; }
</style>
<script>
   function ButtonClick() {
        var iFrameCon = document.getElementById("iFrameCon");
        iFrameCon.style.width = "400px";
        iFrameCon.style.height = "300px";
    }
</script>

关于javascript - resize:在第一次交互之前在JS中更改大小时,两者的行为都不同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17870835/

10-14 21:50
查看更多