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

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

我希望它是这样的

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

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


当前回答

我使用了空的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>

其他回答

在一个“控制”容器中放置几张图像,并更改容器的类。在CSS中,根据容器的类添加规则来管理图像的可见性。这将产生与改变单个图像的img src属性相同的效果。

HTML:

<span id="light" class="red">
    <img class="red" src="red.png" />
    <img class="yellow" src="yellow.png" />
    <img class="green" src="green.png" />
</span>

CSS:

#light         { ... }
#light         *        { display: none; }     // all images are hidden
#light.red     .red     { display: inline; }   // show red image when #light is red
#light.yellow  .yellow  { display: inline; }   // .. or yellow
#light.green   .green   { display: inline; }   // .. or green

注意,它将预加载所有图像,就像CSS的backround-images,但不像通过JS更改img src。

我想补充一点:背景图像也可以用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; 
  (..)
} 
(...)

使用CSS,这是做不到的。但是,如果你正在使用JQuery,像这样的东西可以做到:

$("img.myClass").attr("src", "http://somwhere");

你可以在HTML代码中定义2个图像,并使用display: none;来决定哪一个是可见的。

这里有一个很好的解决方案-> http://css-tricks.com/replace-the-image-in-an-img-with-css/ 正反两方面: (+)与具有相对宽度/高度的矢量图像(RobAu的答案不处理的事情) (+)是跨浏览器的(也适用于IE8+) (+)只使用CSS。所以不需要修改img src(或者如果你没有权限/不想改变已经存在的img src属性)。 (-)抱歉,它使用后台CSS属性:)