Scale and reposition iframe like background-size: cover

后端 未结 2 1584
清酒与你
清酒与你 2020-12-25 11:10

html, body {
         


        
2条回答
  •  独厮守ぢ
    2020-12-25 11:20

    Ok. The merit is NOT mine as I got the jquery here

    I remembered that question as I used it on one of my old projects and I wanted to check if it would work the same with an iframe. It does.

    basically with this css:

    .container {
        position: absolute;
        top: 0;
        overflow: hidden;
    }
    

    and this jquery:

    var min_w = 300; // minimum video width allowed
    var vid_w_orig;  // original video dimensions
    var vid_h_orig;
    
    jQuery(function() { // runs after DOM has loaded
    
        vid_w_orig = parseInt(jQuery('iframe').attr('width'));
        vid_h_orig = parseInt(jQuery('iframe').attr('height'));
    
        jQuery(window).resize(function () { resizeToCover(); });
        jQuery(window).trigger('resize');
    });
    
    function resizeToCover() {
    
        // set the video viewport to the window size
        jQuery('.container').width(jQuery(window).width());
        jQuery('.container').height(jQuery(window).height());
    
        // use largest scale factor of horizontal/vertical
        var scale_h = jQuery(window).width() / vid_w_orig;
        var scale_v = jQuery(window).height() / vid_h_orig;
        var scale = scale_h > scale_v ? scale_h : scale_v;
    
        // don't allow scaled width < minimum video width
        if (scale * vid_w_orig < min_w) {scale = min_w / vid_w_orig;};
    
        // now scale the video
        jQuery('iframe').width(scale * vid_w_orig);
        jQuery('iframe').height(scale * vid_h_orig);
        // and center it by scrolling the video viewport
        jQuery('.container').scrollLeft((jQuery('iframe').width() - jQuery(window).width()) / 2);
        jQuery('.container').scrollTop((jQuery('iframe').height() - jQuery(window).height()) / 2);
    };
    

    You get this: JSFIDDLE

    (I know you were looking for a pure css solution, which I don't think it's possible but I can be wrong, but I have posted this answer because it could help other people with same issue)

提交回复
热议问题