是否可以在CSS中设置src属性值? 在大多数情况下,我们这样使用它:

<img src="pathTo/myImage.jpg" />

我希望它是这样的

<img class="myClass" />
.myClass {
    some-src-property: url("pathTo/myImage.jpg");
}

我想知道是否有一种方法可以做到这一点,而不使用CSS中的background或background-image属性。


当前回答

我想补充一点:背景图像也可以用background-position: x - y来定位;(x水平y垂直)。(. .) 我的例子,CSS:

(..) 
#header {
  height: 100px; 
  background-image: url(http://.../head6.jpg); 
  background-position: center; 
  background-repeat: no-repeat; 
  background-color: grey; 
  (..)
} 
(...)

其他回答

我想补充一点:背景图像也可以用background-position: x - y来定位;(x水平y垂直)。(. .) 我的例子,CSS:

(..) 
#header {
  height: 100px; 
  background-image: url(http://.../head6.jpg); 
  background-position: center; 
  background-repeat: no-repeat; 
  background-color: grey; 
  (..)
} 
(...)

我使用了空的div解决方案,与这个CSS:

#throbber {
    background-image: url(/Content/pictures/ajax-loader.gif);
    background-repeat: no-repeat;
    width: 48px;
    height: 48px;
    min-width: 48px;
    min-height: 48px;
}

HTML:

<div id="throbber"></div>

你可以用JS转换它:

$('.image-class').each(function(){
    var processing = $(this).attr('src');
    $(this).parent().css({'background-image':'url('+processing+')'});
    $(this).hide();
});

不,你不能通过CSS设置图像src属性。你能得到的最接近的是,如你所说,背景或背景图像。我不建议这样做,因为这有点不合逻辑。

但是,如果你的目标浏览器能够使用CSS3解决方案,那么你可以使用它。请使用Pacerier回答中描述的content:url。您可以在下面的其他答案中找到其他跨浏览器的解决方案。

替代方法

.myClass {
background: url('/img/loading_big.gif');
}
<div class="myClass"></div>