简体   繁体   中英

jquery: keep aspect ratio and contain div inside window

I am trying to create a div that will keep it's aspect ratio that maintains a with and height that will not exceed the screen's bounds.

This is the code that I have right now:

<div class="container"></div>

wW=$(window).width();
wH=$(window).height();
wHx=(wW/16)*9;
wWx=(wH/9)*16;
if(wW>wWx){
    vH1=$('.container').height();
    vW1=(vH1/9)*16;
    vP1=($(window).width()-vW1)*0.5;
    $('.container').css('width',vW1+'px');
    $('.container').css('left',vP1+'px');
    $('.container').css('height','100%');
    $('.container').css('top','0');
}
if(wH>wHx){
    vW2=$('.container').width();
    vH2=(vW2/16)*9;
    vP2=($(window).height()-vH2)*0.5;
    $('.container').css('height',vH2+'px');
    $('.container').css('top',vP2+'px');
    $('.container').css('width','100%');
    $('.container').css('left','0');
}

It almost works as intended but it fails in some random situations and the page needs to be refreshed to fix the problem.

Edit: the same function is executed on resize (it fails in some random cases during resize):

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

Edit2: The script fails, after manually resizing the window and then clicking the minimize/maximize button of the browser. I've got the same results with Chrome and Firefox.

This could help

// HTML
<div class="container"></div>

// CSS (SASS)
.container {
  background: red;
  max-width: 100%;

  &:before {
    content: '';
    display: block;
    // for 16/9 this is the height you need
    padding-top: 56.25%;

  }
}

// JavaScript
$(function(){
  $(window).resize(function(){
    var width  = $(window).width(),
        height = $(window).height();

    if (width/height > 16/9) {
      $('.container').css('max-width', height * 16 / 9);
    } else {
      $('.container').css('max-width', '100%');
    }
  })
  // trigger resize so it takes the
  // right size on load
  .trigger('resize');

});

examle http://codepen.io/istavros/full/vxwVoW/

I believe this is what you are looking for:

<div class="container"></div>
//CSS
.container {
max-width: 100vw;
max-height: 100vh;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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