简体   繁体   中英

JQuery: Resize image based on browser resizing

I am attempting to resize an image based on the size/resizing of the browser using JQuery.

I want the image to scale and maintain it's ratio and not get cut off.

I'm using Bootstrap and my HTML looks like this:

<div class="container-fluid">
      <div class="row">
        <div class="col-sm">
          <div class="text-block">
            <h1>Hellow World</h1>
            <h6>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</h6>
          </div>
        </div>
        <div class="col-sm img-container">
          <img src="image.png" />
        </div>
        <div class="col-sm">
          <div class="text-block">
          <h6>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</h6>
          </div>
        </div>
      </div>
    </div>

The image is within the .img-container div and my JQuery looks like this:

$(document).ready(function() {
   $(window).resize(function() {
     var img = $("img");
     var image = $(".img-container").find(img);
     var browserRatio =  $(this).width() / $(this).height();
     var imageRatio = image.width() / image.height();

     if(browserRatio > imageRatio) {
       $(".img-container").find(img).css({ "width": "100%", "height": "auto"});
     }
     else if(imageRatio > browserRatio) {
       $(".img-container").find(img).css({ "width": "auto", "height": "100%"});
     }

     console.log("Browser ratio is :" + browserRatio);
     console.log("Image ratio is:" + imageRatio);
   });
});

As you can see I am grabbing the height/width ratio of the browser as it resizes and then checking if the image's ratio is greater or less than the ratio of the browser and then attempting to adjust it using css.

This is not working and the width of the image is not maintaining it's ratio. What's wrong with my code?

Recently I have answered the same question by simply using CSS https://jsfiddle.net/nazimboudeffa/j6kwtgxa/

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

img {
  padding: 0;
  display: block;
  margin: 0 auto;
  max-height: 100%;
  max-width: 100%;
}

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