简体   繁体   中英

fullscreen & centred background image script

I have made a simple function that adapts the size of an image according to the size of the window. I can't determine when exactly, but sometimes the img does not fill the width of the screen, but continues to stick to the height. Any idea why this could be?

If i console log (iRatio <= wRatio) anything seems to fit, but the shown result is incorrect.

The img is set as postion: absolute; with: 100%; top:0; left:0; postion: absolute; with: 100%; top:0; left:0; in the css. $win contains $(window) and $img the background image

function autoImageSize($img, $win){
        var wHeight = $win.height(),
            wWidth = $win.width(),
            iHeight = $img.height(),
            iWidth = $img.width(),
            iRatio = iWidth / iHeight, 
            wRatio = wWidth / wHeight;

          if(iRatio <= wRatio){
            $img.css({
               width: "100%", 
               height: "auto",
               top: "-" + ((iHeight - wHeight)/2) + "px",
               left: 0
            });
          }else{
            $img.css({
               width: "auto", 
               height: "100%",
               top: 0,
               left: "-" + ((iWidth - wWidth)/2) + "px"
             });
          }

          return [$img.width(), $img.height()];
};

the problem was:

left: "-" + ((iWidth - wWidth)/2) + "px"

and

top: "-" + ((iHeight - wHeight)/2) + "px"

this is a stupid way to do a negation, sometimes the result was --somenumber px. i fixed the problem by doing this operation only wen the iHeight is smaller then the wHeight oder the iWidth is smaller then wWidth and by calculating the negation with a multiplication by -1.

When you are setting the image's width to 100% it will fill up to its parent's width. As is the case with the height of 100%, but there the parent also needs a fixed height in pixels (as far as I know).

Instead of setting the height to 100% you should calculate the width matching the height of the window using the image's ratio:

var toWidth = $win.height() * iRatio;
$img.width(toWidth);

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