Jquery 在不知道背景高度的情况下使用背景设置div height

Jquery 在不知道背景高度的情况下使用背景设置div height,jquery,html,css,height,masonry,Jquery,Html,Css,Height,Masonry,我有很多相同的div。每个人都有自己的背景 <div class="grid-item"><div class="grid-con" style="background:url(http://image-goes-here.com/img.jpg);"></div></div> // etc... 和css以获得额外属性: .masonry { float:left; width:950px; margin-top:20px; } .grid {

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

<div class="grid-item"><div class="grid-con" style="background:url(http://image-goes-here.com/img.jpg);"></div></div>
// etc...
和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
,一切正常

问题:


如何使它在没有固定高度的情况下工作<代码>宽度:100%工作正常,但
高度:auto
不工作。我需要显示所有需要适应固定宽度和未知高度的背景。

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

$('.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或更早版本(),也可以使用图像的
自然高度

为什么要使用jQuery设置背景属性?为什么不直接用CSS呢?当你说
height:auto
不起作用时,你是什么意思?发生了什么,你希望发生什么?请阅读。因为如果我将jQueryCSS属性设置为css文件,它将不起作用。若我直接设置为code,它的工作原理和jquery方法相同。例如,我有一个图像,它需要适应固定宽度和未知高度,但我需要显示自动计算的高度。此外,我需要使用背景方法,而不是
方法。
$('.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);
  }
});