首页 文章

动态调整iframe的大小

提问于
浏览
8

Situation: 我'm working on a responsive design that involves the typical HTML/CSS combo. Everything is working nicely except in one case where there is an iframe inside of a div. The iframe should adjust automatically to the size of the parent div. A purely css solution has not presented itself so I'采用JQuery方法 . 除了在一个场景中,从较小宽度调整到较大宽度屏幕时,它的效果很好 .

HTML:

<div class="container">
    <iframe class="iframe-class" src="http://www.cnn.com/"></iframe>
</div>

CSS:

.container {
    width: 100%;
    height: 250px;
}
.iframe-class {
    width: 100%;
    height: 100%;
    border: 1px solid red;
    overflow: auto;
}

Javascript:

$(function () {
    setIFrameSize();
    $(window).resize(function () {
        setIFrameSize();
    });
});

function setIFrameSize() {
    var ogWidth = 700;
    var ogHeight = 600;
    var ogRatio = ogWidth / ogHeight;

    var windowWidth = $(window).width();
    if (windowWidth < 480) {
        var parentDivWidth = $(".iframe-class").parent().width();
        var newHeight = (parentDivWidth / ogRatio);
        $(".iframe-class").addClass("iframe-class-resize");
        $(".iframe-class-resize").css("width", parentDivWidth);
        $(".iframe-class-resize").css("height", newHeight);
    } else {
        // $(".iframe-class-resize").removeAttr("width");
        // $(".iframe-class-resize").removeAttr("height");
        $(".iframe-class").removeClass("iframe-class-resize");
    }
}

http://jsfiddle.net/TBJ83/

Problem: 当窗口调整得更小时,它会不断检查窗口宽度,一旦达到<480 px,代码就会添加一个名为 iframe-class-resize 的类,并将宽度和高度设置为该类 . 随着窗口调整大小,一旦大小达到480像素,它将删除该类 . 问题是设置width和height属性会将它们直接添加到元素而不是类本身 . 因此,删除类不会删除新的宽度和高度 . 我尝试使用 removeAttr() (上面已注释掉)强制删除属性,但这不起作用 .

有人看到上面的代码出错了吗?或者有关如何更有效地完成响应式iframe的任何建议?所需的主要内容是iframe必须位于 <div></div> 内,div可能不一定定义宽度或高度 . 理想情况下,父div应该明确定义宽度和高度,但这个网站当前的设置方式,并不总是可行的 .

Additional: 如果上述情况不够清楚,请尝试以下方法重现问题:

  • 在台式机上打开浏览器 . 我'm using Chrome on a Windows machine. Don' t最大化浏览器 .

  • 打开上面的jsfiddle(http://jsfiddle.net/TBJ83/) . 您会注意到iframe内容跨越了“预览”面板的整个宽度 .

  • 手动调整宽度,直到整个窗口<480px . 此时,iframe内容将非常小 .

  • 手动调整宽度,直到整个窗口为>> 480px . 目标是让iframe内容重新获得预览面板的整个宽度 . 相反,内容保留调整大小的宽度和高度,因为 .css() 函数将css更改直接应用于元素而不是类 .

提前致谢!

4 回答

  • 0

    您可以使用大约30个字符执行此操作 . 更改:

    $(".iframe-class").removeClass("iframe-class-resize")
    

    至:

    $(".iframe-class").removeClass("iframe-class-resize").css({ width : '', height : '' })
    

    这将重置您应用于元素的宽度/高度 . 当您使用 .css() 时,您将传入的任何内容添加到元素的 style 属性中 . 传递空值时,jQuery会从元素的 style 属性中删除该属性 .

    这是一个更新的小提琴:http://jsfiddle.net/TBJ83/3/

    EDIT

    好的,这里有针对性能调整的东西(以及其他一些方法):

    $(function () {
    
        //setup these vars only once since they are static
        var $myIFRAME   = $(".iframe-class"),//unless this collection of elements changes over time, you only need to select them once
            ogWidth     = 700,
            ogHeight    = 600,
            ogRatio     = ogWidth / ogHeight,
            windowWidth = 0,//store windowWidth here, this is just a different way to store this data
            resizeTimer = null;
    
        function setIFrameSize() {
            if (windowWidth < 480) {
    
                var parentDivWidth = $myIFRAME.parent().width(),//be aware this will still only get the height of the first element in this set of elements, you'll have to loop over them if you want to support more than one iframe on a page
                    newHeight      = (parentDivWidth / ogRatio);
    
                $myIFRAME.addClass("iframe-class-resize").css({ height : newHeight, width : parentDivWidth });
            } else {
                $myIFRAME.removeClass("iframe-class-resize").css({ width : '', height : '' });
            }
        }
    
        $(window).resize(function () {
    
            //only run this once per resize event, if a user drags the window to a different size, this will wait until they finish, then run the resize function
            //this way you don't blow up someone's browser with your resize function running hundreds of times a second
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {
                //make sure to update windowWidth before calling resize function
                windowWidth = $(window).width();
    
                setIFrameSize();
    
            }, 75);
    
        }).trigger("click");//run this once initially, just a different way to initialize
    });
    
  • 1

    我就是这样做的,代码要短得多: http://jsfiddle.net/TBJ83/2/

    <div class="container">
        <iframe id="myframe" src="http://www.cnn.com/"></iframe>
    </div>
    
    <script>
    $(function () {
        setIFrameSize();
        $(window).resize(function () {
            setIFrameSize();
        });
    });
    
    function setIFrameSize() {
        var parentDivWidth = $("#myframe").parent().width();
        var parentDivHeight = $("#myframe").parent().height();
        $("#myframe")[0].setAttribute("width", parentDivWidth);
        $("#myframe")[0].setAttribute("height", parentDivHeight);
    }
    </script>
    

    我这样做是为了读取能力,但你可以让它更短更快......

    function setIFrameSize() {
        f = $("#myframe");
        f[0].setAttribute("width", f.parent().width());
        f[0].setAttribute("height", f.parent().height());
    }
    

    一个选择器,因此您只需查看DOM一次而不是多次 .

  • 0

    对于那些使用Prestashop的人来说,这就是我使用代码的方式 .

    在cms.tpl文件中,我添加了以下代码:

    {if $cms->id==2}
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
    <script type="text/javascript" src='../themes/myheme/js/formj.js'></script>
    <div style="width: 100%; height: 800px;">
    <iframe style=" width: 100%; height: 100%; border: overflow: auto;" src="https://cnn.com"></iframe>
    </div>
    {/if}
    

    然后创建了一个新的js文件:formj.js并添加了以下代码:

    $(function () {
    
        //setup these vars only once since they are static
        var $myIFRAME   = $(".iframe-class"),//unless this collection of elements changes over time, you only need to select them once
            ogWidth     = 970,
            ogHeight    = 800,
            ogRatio     = ogWidth / ogHeight,
            windowWidth = 0,//store windowWidth here, this is just a different way to store this data
            resizeTimer = null;
    
        function setIFrameSize() {
            if (windowWidth < 480) {
    
                var parentDivWidth = $myIFRAME.parent().width(),//be aware this will still only get the height of the first element in this set of elements, you'll have to loop over them if you want to support more than one iframe on a page
                    newHeight      = (parentDivWidth / ogRatio);
    
                $myIFRAME.addClass("iframe-class-resize").css({ height : newHeight, width : parentDivWidth });
            } else {
                $myIFRAME.removeClass("iframe-class-resize").css({ width : '', height : '' });
            }
        }
    
        $(window).resize(function () {
    
            //only run this once per resize event, if a user drags the window to a different size, this will wait until they finish, then run the resize function
            //this way you don't blow up someone's browser with your resize function running hundreds of times a second
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {
                //make sure to update windowWidth before calling resize function
                windowWidth = $(window).width();
    
                setIFrameSize();
    
            }, 75);
    
        }).trigger("click");//run this once initially, just a different way to initialize
    });
    
  • 8

    这可以使用纯CSS完成,如下所示:

    iframe {
      height: 300px;
      width: 300px;
      resize: both;
      overflow: auto;
    }
    

    将高度和宽度设置为您想要的最小尺寸,它似乎只是增长而不是缩小 .

相关问题