Can I replace an image tag’s image with CSS?

蹲街弑〆低调 提交于 2019-12-13 08:35:27

问题


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.


回答1:


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; }



回答2:


you could hide the image itself:

img#someid { display: none; }

and then (or before that if you wish) set background on the parent element.




回答3:


I'm not quite sure what you mean with 'hide the image of the src attribute' but if you mean hide the link/path of the image you are displaying, using CSS (even as a background image) then the answer is no, not that I'm aware of. People can easily view your CSS file. The only real way to hide it is with JS, but even with that you can disable the JS from the client and still view it. You could put it in a DB like MySQL and display it using PHP but even at that, the image path would still be shown.




回答4:


Would you be able to wrap the img in a div with no padding/margin, and make the img's display attribute to hidden (via js) so the div's background would be shown.

But honestly, if you take the trouble to do this, you should just swap the src of the image via js.



来源:https://stackoverflow.com/questions/10119461/can-i-replace-an-image-tag-s-image-with-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!