我可以用CSS替换图片标签的图片吗? [英] Can I replace an image tag’s image with CSS?

查看:107
本文介绍了我可以用CSS替换图片标签的图片吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我无法使用CSS更改< img> 标签的 src 属性。但是,是否有可能将图像从src属性中隐藏起来,并在< img> 标签上设置背景图像?



我认为这样的事情:将实际的图像用填充/文本打算等移出视图,然后设置img-tag的背景图像,所以它看起来像一个其他的图像。



Js不是一个选项,因为它是关于对现有页面进行模板化的。

解决方案

您可以通过将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; }

这篇关于我可以用CSS替换图片标签的图片吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆