简体   繁体   English

如何使用CSS更改图像源?

[英]How do I change an image source with CSS?

I would like to change the displayed image just with CSS 我想用CSS改变显示的图像

<a href="/"><img id="image1" src="http://somepic.jpg"></a>

since there is no css for src I think, I must make it transparent and display another image in the background somehow? 因为我认为src没有css,我必须让它透明并在某种程度上在后台显示另一个图像?

You can't. 你不能。 You could change it with Javascript. 你可以用Javascript改变它。

With CSS, you could set the image to display:none; 使用CSS,您可以将图像设置为display:none; set a background-image on a parent element. 在父元素上设置background-image

I would suggest the following alternatives: 我会建议以下替代方案:

  • (especially) If the <img> s lend no semantic value, remove them entirely in favor of putting background-image s on other elements. (特别是)如果<img>没有语义值,则完全删除它们以支持将background-image s放在其他元素上。
  • If the new images lend semantic value to the document, and you're ok with them being pre-loaded, insert them as additional <img> s and just hide one or the other with css (assuming this is for a hover or other similarly conditional effect) 如果新图像为文档提供了语义值,并且您可以预先加载它们,则将它们作为附加<img>插入并使用css隐藏其中一个(假设这是用于hover或其他类似的条件效应)
  • Change the src with javaScript 使用javaScript更改src

Although its true that CSS is made for presentation only but CAS (Cascading Attribute Sheet) is been proposed and under thought, also I think for basic purpose below code should work for you , 尽管CSS仅用于演示,但CAS(级联属性表)已经被提出并且在思考之下,我认为对于基本目的而言下面的代码应该对你有用,

<style>
a:after
{
content:url(your_image.jpg);
}
#image1
{
display:none;
}
</style>

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

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