繁体   English   中英

全屏和居中背景图片脚本

[英]fullscreen & centred background image script

我做了一个简单的函数,可以根据窗口的大小调整图像的大小。 我无法确定确切的时间,但有时img不会填充屏幕的宽度,而是会继续保持高度。 知道为什么会这样吗?

如果我在控制台日志(iRatio <= wRatio)中显示任何内容,但显示的结果不正确。

img设置为postion: absolute; with: 100%; top:0; left:0; postion: absolute; with: 100%; top:0; left:0; 在CSS中。 $win包含$(window)$img背景图片

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()];
};

问题是:

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

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

这是一种否定的愚蠢方法,有时结果是--somenumber px。 我通过仅在iHeight小于wHeight或iWidth小于wWidth的情况下执行此操作来解决此问题,并通过乘以-1计算负数。

将图像的宽度设置为100%时,它将填满其父图像的宽度。 与高度为100%的情况一样,但父级也需要一个固定的像素高度(据我所知)。

而不是将高度设置为100%,您应该使用图像的比例来计算与窗口高度匹配的宽度:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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