且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以用CSS替换图片标签的图片吗?

更新时间:2023-02-09 12:24:55

您可以通过将img src指向1x1空白gif图像来完成此操作。

如果您不想添加另一个div,这是必需的,因为所有浏览器都会以不同方式处理丢失图像和空src属性。 (如果图像缺失,chrome将在图像周围添加边框)。

然后,您可以通过更改背景图像属性来更改图像。 p>

更新



您也可以为其创建图片精灵并通过更改背景位置属性。例如:

假设您有两张50像素宽的图像,并且您希望第二张图像显示该元素是否被徘徊。只需将它们合并到一个图像中,上面的css就可以实现这个功能。

  img {background:url(sprite.jpg) )0 0无重复; } 
img:hover {background:url(sprite.jpg)-50px 0 no-repeat; }


I know I can't change the src attribute of an <img> tag with CSS. But is there a possiblity to hide the image from the src attribute, and set a background image on the <img> tag instead?

i thought something like that: moving the actual image with padding/text-intend etc. out of view and after that setting the background-image of the img-tag, so it looks like an other image.

Js is not an option, because it's about templating an existing page.

You can do that by pointing the img src to a 1x1 blank gif image.

This is necessary if you don't want to add another div since all browsers handle missing images and empty src attributes differently. (chrome will add a border around the image if the image is missing for instance.)

Then you can change the images just by changing the background-image property.

UPDATE

You can also create image sprites for that and animate them by altering the background-position property. For instance:

Lets say that you have two 50px wide images and you want the second one to show when that element is hovered. Just merge them together in one image, and the css above would do the trick.

img { background: url(sprite.jpg) 0 0 no-repeat; }
img:hover { background: url(sprite.jpg) -50px 0 no-repeat; }