我有以下html:
<div class="A">
<img src="image1.png" width="100px" height="100px"/>
</div>
在我的媒体查询 CSS 样式表中,我想将该图像替换为另一张图像 (image2.png)。
我需要写什么css代码?
我尝试了以下方法:
.A img
{
background:url("image2.png") no-repeat;
}
但这似乎不正确?
如果您使用 CSS3,那么
content
就是答案:
.A img
{
content: url("image2.png");
}
你不能在 CSS 中修改它,而是使用这样的 div:
<div id='#theImage'></div>
然后在 CSS 中:
#theImage {
width:100px;
height:100px;
background:url("image1.png") no-repeat;
}
然后您可以使用媒体查询重新设置 div 的样式。
您的代码不起作用,因为原始
<img>
标签中的图像是前景图像,与背景图像不同。
因此设置 CSS 并不会删除原始图像。此外,虽然 CSS 确实有效,但它显示的背景图像显示在前景图像后面。
为了做到这一点,您需要将原始图像作为背景图像(即使用 CSS
background-image
属性设置),或者切换到替换脚本中的前景图像。这将涉及设置 src
属性:
$('.a img').attr('src','newimage.png');
您正在设置您看不到的
img
元素的背景,因为其 src
属性中定义的图像覆盖了它
无论如何,如果从语义的角度来看这两个图像都与上下文相关,则不应使用 css 来放置第二个图像来代替第一个图像
.image-replacement {
display: block;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: url(https://www.whatsappimages.in/wp-content/uploads/2021/07/Top-HD-sad-quotes-for-whatsapp-status-in-hindi-Pics-Images-Download-Free.gif)
no-repeat;
width: 180px;
height: 236px;
padding-left: 180px;
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Image replaced with Image</h2>
<img class="image-replacement" src="https://images.unsplash.com/photo-1503023345310-bd7c1de61c7d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW58ZW58MHx8MHx8&w=1000&q=80" />
</body>
</html>
.image-replacement {
display: block;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: url(https://www.whatsappimages.in/wp-content/uploads/2021/07/Top-HD-sad-quotes-for-whatsapp-status-in-hindi-Pics-Images-Download-Free.gif)
no-repeat;
width: 180px;
height: 236px;
padding-left: 180px;
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Image replaced with Image</h2>
<img class="image-replacement" src="https://images.unsplash.com/photo-1503023345310-bd7c1de61c7d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW58ZW58MHx8MHx8&w=1000&q=80" />
</body>
</html>