简体   繁体   English

仅使用CSS设置图像源

[英]set image source using css only

I'd like to load images and their contents dynamically from a css file. 我想从css文件动态加载图像及其内容。 I know I can set the background-image attribute for divs, but how can I achieve something similar for images? 我知道可以为div设置background-image属性,但是如何为图像实现类似的功能?

You can't. 你不能

The <img> element holds content. <img>元素保存内容。 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. 您可以将img的src设置为透明的gif,并设置img的背景图像,就像设置div一样,但这有点麻烦。 You can change the src attribute of an image very easily using javascript: 您可以使用javascript轻松更改图像的src属性:

html: HTML:

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

javascript: JavaScript的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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