简体   繁体   中英

set image source using css only

I'd like to load images and their contents dynamically from a css file. I know I can set the background-image attribute for divs, but how can I achieve something similar for images?

You can't.

The <img> element holds content. The specifics of that content aren't something that can, or should, be described on the presentation layer.

You can set the src of the img to a transparent gif and set the background image of the img just like you would a div but that's a bit of a hack. You can change the src attribute of an image very easily using javascript:

html:

<img id="asdf" src="1.gif"  />

javascript:

document.getElementById("asdf").setAttribute("src","2.gif");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM