JenkinsY
JenkinsY

Reputation: 167

change image manually as window sizes

I used js to set image width and height according to window size. But in some cases when the browser is very wide, the image's hight exceeds all its father element's height. As a result, the bottom part of the image is not shown. How can I solve this?

I used bootstrap and swiper in this project and the image I want to change is inside my swiper division. I set and all the image's father elements' height to 100%. Here is my js code to change is image dymanically. The image size is 2560*1440.

if(winWidth/winHeight < 2560/1440) {
     imgHeight = winHeight;
     imgWidth = winHeight/1440 * 2560;
     }else {
     imgWidth = winWidth;
     imgHeight = winWidth/2560 * 1440; 
     }
    attr = "width:" + imgWidth + 'px;height:' + imgHeight + 'px;margin-left: -' + imgWidth/2 + 'px;margin-top:-' + imgHeight/2 + 'px';
    $('.main .swiper-slide > img').attr('style',attr);

PS: Sorry I didn't make it clear. The following methods you provided scale the image down in vertical view and so leaves much blank in the page. Actually I want my image's height to occupy the whole window's height, no matter in vertical window or horizontal window. And if the window is wide enough, image's width equals the window's width, otherwise cut the image in width and make it equals the window's width too.

Upvotes: 1

Views: 103

Answers (1)

ghost_dad
ghost_dad

Reputation: 1306

@patstuart is correct, this is much better handled directly through CSS. It's pretty amazing how many styling issues (go figure) can be solved without writing a single line of JavaScript. So to answer your second question, let's figure out how it can be done with CSS. Without seeing a fiddle or your actual page / image, I'll just shoot from the hip here. If I understand correctly, you want the full image to display at its correct ratio no matter what the width / height of the screen is. If that's the case, here's a nice little trick:

.main .swiper-slide {
  width: 100%;
  height: 0;
  /* Padding bottom should be the height's ratio to the width.
     Which in this case, would be 56.25% */ 
  padding-bottom: 56.25%;
}
.main .swiper-slide > img {
  width: 100%;
}

That is how aspect ratio can be handled with CSS. Let me know if that resolves your issue or if you have any other questions. CSS was made for styling so always look for a solution there first.

Upvotes: 1

Related Questions