在不知道背景高度的情况下设置 div 带背景的高度

Set div height with background without knowing background height

我有很多相同的 div。每个人都有自己的背景。

<div class="grid-item"><div class="grid-con" style="background:url(http://image-goes-here.com/img.jpg);"></div></div>
// etc...

我正在使用 jQuery 将属性设置为背景:

$(".grid-con").css({"background-size": "100% auto", "background-repeat": "no-repeat", "background-position": "50% 50%"});

和 css 额外属性:

.masonry { float:left; width:950px; margin-top:20px; }
.grid { width:100%;  }
.grid-item { width:217px; margin:0 20px 20px 0; }
.grid-con { width:100%; height:auto; }

一切正常,如果我将固定高度设置为 .grid-con

问题:

如何让它在没有固定高度的情况下工作? width:100% 完美,但 height:auto 不完美。我需要显示所有需要适应固定宽度和未知高度的背景。

我不确定 this demo 的结果是否符合您的预期,但代码如下:

$('.grid-con[style*=url]').each(function(){
  var $this = $(this),
    img = new Image(),
    src = $this.attr('style').match(/url\(([^)]+)/);
  if ( src && src.length >= 1 ) {
    img.src = src[1];
    $this.height(img.height);
  }
});

如果您不支持 IE8 或更早版本 (ref),您也可以使用图像的 naturalHeight