Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

scale - Proportionally resize iframe to fit in a DIV using jQuery

I have an iframe of a video inside a div, like so:

<div class="media">
    <iframe>
</div>

I set the DIV's size dynamically on window resize.

I want to scale the iframe to fit inside the div, while maintaining it's aspect ratio. Most of the code out there deals with scaling images, which is easier.

This is what I have so far, but it doesn't work:

jQuery.fn.fitToParent = function()
{
    this.each(function()
    {
        var width  = jQuery(this).width();
        var height = jQuery(this).height();
        var parentWidth  = jQuery(this).parent().width();
        var parentHeight = jQuery(this).parent().height();

        if(width < parentWidth)
        {
            newWidth  = parentWidth;
            newHeight = newWidth/width*height;
        }
        else
        {
            newHeight = parentHeight;
            newWidth  = newHeight/height*width;
        }

        jQuery(this).css({
            'height'     :newHeight,
            'width'      :newWidth'
        });
    });
};

Basically, I'm looking to replicate the sizing that "background-size: contain" does for images in CSS, but for an iframe in a DIV.

Thanks for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Three issues noted:

  1. You have an error (trailing quote) in your example:

    :newWidth'

  2. You need to set the iframe actual height and width attributes and not the style. Styling an iframe size has no effect:

    $(this).width(newWidth);
    $(this).height(newHeight);
    
  3. the calculation for aspect ratio was wrong (needs to compare ratios to see which way they overlap). Without this not all overlap cases are catered for.

    var aspect = width/height;
    var parentAspect = parentWidth/parentHeight;
    if (aspect > parentAspect)
    {
        newWidth  = parentWidth;
        newHeight = newWidth / aspect;
    }
    else
    {
        newHeight = parentHeight;
        newWidth  = newHeight * aspect;
    }
    

I also cleaned up the code a little to speed up element access. Each call to jQuery(this) costs cycles.

JSFiddle here: http://jsfiddle.net/TrueBlueAussie/ZJDkF/8/

Updates:

The jsfiddle now has examples of the 4 different scenarios of overlap and each retains the proportions of the iframe. I also added the window resize you mentioned and made the first div resize dynamically with it to demonstrate.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...