如何在<img>标签上模拟background-size: cover?

69

如何调整并重定位盒子内的图像,使其覆盖整个盒子,类似于background-size: cover的工作方式。

<div class="box" style="width: 100px; height: 100px;">
  <img src="pic.jpg" width="413" height="325">
</div>

我知道我需要在盒子中添加overflow:hidden,并且图像需要position:absolute。但是,有什么公式可以让我得到正确的图像新尺寸以及左侧和顶部位置吗?


$('.box').each(function(i) { $(this).children('img:first').height($(this).height()).width($(this).width()).css({ position: 'absolute', top: 0, left: 0 }); }) - SpYk3HH
@SpYk3HH 这与 background-size: cover 不同,而是相同的 background: 100% 100% - MattDiamant
你想要图片也居中还是只是足够大?我正在看这个示例,它不会将图像居中。http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=cover - TreeTree
不太确定你想要什么,因为覆盖是固有的背景定位。这似乎对于内部img元素来说有点不好的姿势,但我想你可以尝试一个精确的公式,虽然我自己也不确定那个公式。 - SpYk3HH
@TreeTree:是的,那是我的错误。我以为背景大小覆盖也会居中图片 :P (也许还需要背景位置:中心?) - Alex
我认为将其设置为居中只有在图像比容器小的情况下才起作用。如果您的图像是容器大小的两倍,它仍将定位到左上角。 - TreeTree
15个回答

1

0
我创建了下面的函数来实现它。我从已接受的答案中借用了一些逻辑,并调整它以适用于任何容器,通过创建图像尺寸:容器尺寸的比率,然后比较哪个更大来确定要调整的尺寸。还添加了一个“center”参数(“true”居中,“false”将其设置为顶部/左侧)。
我正在使用带有translateX/Y的CSS3,但可以轻松地在没有它的情况下使其工作。
以下是代码:
var coverImage = function(wrap, center) {

  if (typeof center === 'undefined') {
    center = true;
  }

    var wr = $(wrap),
        wrw = wr.width(),
        wrh = wr.height();

  var im = wr.children('img'),
        imw = im.width(),
        imh = im.height();

  var wratio = wrw / imw;
    var hratio = wrh / imh;

  //Set required CSS
  wr.css({'overflow' : 'hidden'});
  im.css({'position' : 'relative'});


  if (wratio > hratio) {
    im.width(wrw);
    im.css({'height' : 'auto'});

    if (center) {
      im.css({
        'top' : '50%',
        'transform' : 'translateY(-50%)'
      });
    }
  } else {
    im.height(wrh);
    im.css({'width' : 'auto'});

    if (center) {
      im.css({
        'left' : '50%',
        'transform' : 'translateX(-50%)'
      });
    }
  }
}

并且可以查看 jsfiddle 来查看它的实际效果: https://jsfiddle.net/cameronolivier/57nLjoyq/2/


0

对于像我今天一样寻找适用于横向、纵向、矩形、正方形等各种图像和任意容器尺寸的解决方案的任何人,我在下面附上了自己的代码。

这个解决方案也可以实现响应式,只需在窗口大小改变时再次运行即可。

JSFiddle:

http://jsfiddle.net/66c43ao1/

HTML

<div class="test">
    <div class="cover">
        <img src="http://d2ws0xxnnorfdo.cloudfront.net/character/meme/cool-dog.jpg" width="590" height="590"/>
    </div>
</div>

CSS

/* modify the width and height below to demonstrate coverage */
.test {
    height: 300px;
    position: relative;
    width: 500px;
}
/* you will need the below styles */
.cover {
    height: 100%;
    left: 0;
    overflow: hidden;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: 1;
}

JS

$('.cover').each(function() {
    var containerHeight = $(this).height(),
        containerWidth  = $(this).width(),
        image           = $(this).children('img'),
        imageHeight     = image.attr('height'),
        imageWidth      = image.attr('width'),
        newHeight       = imageHeight,
        newWidth        = imageWidth;

    if (imageWidth < containerWidth) {
        // if the image isn't wide enough to cover the space, scale the width
        newWidth        = containerWidth;
        newHeight       = imageHeight * newWidth/imageWidth;
    }
    if (imageHeight < containerHeight) {
        // if the image isn't tall enough to cover the space, scale the height
        newHeight       = containerHeight;
        newWidth        = imageWidth * newHeight/imageHeight;
    }

    var marginLeft      = (newWidth - containerWidth)/2;
    var marginTop       = (newHeight - containerHeight)/2;

    image.css({
        marginLeft  : '-' + marginLeft + 'px',
        marginTop   : '-' + marginTop + 'px',
        height      : newHeight,
        width       : newWidth
    });
});

当然,您可以使用像Backstretch这样的库来完成相同的事情,但我发现这个解决方案更适合我的目的(没有增加依赖项,更轻量级等)。

0

我做了一些东西,可以模拟 background-size:coverbackground-position:center

如果你想改变位置,只需更改图像的 "top" 和 "left" 样式。

CSS

.box{
    overflow:hidden;
    position:relative;
}

.box img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
}

JS

$('.box').each(function() {
     //aspect ratio of container
     var boxRatio = $(this).height() / $(this).width(); 
     //aspect ration of image
     var imageRatio = $(this).children('img').height() / $(this).children('img').width();
     //set width or height 100% depend of difference
     if (imageRatio > boxRatio) {
          $(this).children('img').css({"width":"100%","height":"auto"});                
     } else {
          $(this).children('img').css({"height":"100%","width":"auto" });
     }
});

这个函数应该在“load”和“resize”事件上被激活。


0
如果您想让图像在框中居中而不调整图像大小,只需使用此代码:

.box {
    width: 100px;
    height: 100px;
    overflow: hidden;
    position: relative;
}
.box img {
    width: 413px;
    height: 325px;
    position: absolute;
    left: 50%;
    top: 50%;
}

如果你想要调整图像的大小以适应,可以使用以下代码:
.box {
    width: 100px;
    height: 100px;
}
.box img {
    width: 100%;
    height: auto;
}

如果图像的宽度大于高度,此代码将留下一些空白。如果这两种方法都不起作用,您可以将图像设置为背景,并使用background-size: cover;


1
如果图片是横向的会发生什么? - FiLeVeR10
第一段代码就像透过一个小孔看图片一样,只要图片比盒子大,盒子就会被填满。对于第二段代码,横向的图片会在其下方留出空白(根据您的填充情况也可能在上方留出空白)。为了避免这种情况,您可以添加第二张图片并删除所有填充和边距。 - zsaat14

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接