开发者

css - how to change image source by its id?

Does anyone know how can I control the image source from the CSS?

I need to be able to change the image src from the CSS. I have loop printing < img id=.. > tags, and for every id it different image. I want to be able to set the source by it开发者_开发技巧s id from the style css area.

Does anyone know how to do this?


This is not possible: The image's source is part of the markup, not CSS.

The only workaround would be having div elements with background-image properties instead. Those you could set from within the style sheet:

<div id="image1"></div>

#image1 { width: 100px; height: 50px; background-image: url(image.gif); }

However, with this method you lose all the img tag's advantages like

  • The ability to set an alt text
  • Resizing
  • Printing (most browsers don't print background images)
  • Search engine indexing (probably)

the only other alternative is by using JavaScript, but that obviously won't work if JavaScript is disabled, which makes it a no-no in my view.


This is now possible with CSS3 using the Content style. I use this to swap images within a slider based on window size through media queries.

Edit: When I originally posted this, I was unaware that it only worked in Webkit at the moment. But I doubt it will take long before it gains more functionality across browsers.

HTML

<img class="img1" src="image.jpg">

CSS

@media (min-width: 768px) {
    .img1 {
      content: url(image.jpg);
    }
}
@media (max-width: 767px){
    .img1 {
      content: url(new-image.jpg);
    }
}


That is not possible with CSS. However, this is very easy with Javascript:

 document.getElementById("IdOfImage").src = "SourceOfImage";


You cannot really do that, however, if you do need to do that using CSS, you can do it for two images with the same size like this:

<style>
img {
  width:0;
  height:0;
  display:block;
  background: url('2.png') no-repeat bottom left;
  padding-left:196px;
  padding-bottom:187px;
}
</style>
<img src="1.png">

Only tested it in FF3.6 though.


I found this article that might be useful. It actually changes background of an image

here is the example in case website goes missing:

HTML

<html>
    <body>
        <div class="header">
            <img class="banner" src="http://notrealdomain1.com/banner.png">
        </div>
    </body>
</html>

CSS

/* All in one selector */
.banner {
    display: block;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: url(http://notrealdomain2.com/newbanner.png) no-repeat;
    width: 180px; /* Width of new image */
    height: 236px; /* Height of new image */
    padding-left: 180px; /* Equal to width of new image */
}


If you don't want to use backgrounds nor use javascript, you layer 2 images with different src on top of each other (using absolute positioning) and use CSS to hide one or another. Visually it will be the same then changing the src.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜