为了我的一生,当图像缺少alt或alt为空时,我试图找到一种简单的方法在图像上叠加颜色。我已经能够找到正确的代码来发现alt是否确实丢失了。如果我输入宽度:50px;我可以更改图像的大小,但是我正在寻找颜色覆盖层。我正在尝试将其创建为CSS。
我看过这里的其他文章,但它们似乎更多是关于悬停,而这并不是我想要的。
img[alt=""] {width: 50px;}
尝试以下类似方法。它将我的初始答案与PossessWithin结合在一起。您可以利用<figure/>
元素的常规语义语法以及同级和伪元素来在整个<figure/>
上创建覆盖。
[不幸的是,您必须在<figure/>
周围附加标记才能使它起作用,因为去回答此类问题(使用伪<img>
元素)将不适用于:after
。参见<img>
Does :before not work on img elements?
.container {
position: relative;
}
img:not([alt])+.label::after {
content: "missing alt";
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(255, 0, 0, 0.2);
}
您也可以按照<figure class="container">
<img src="https://via.placeholder.com/150" width="150" height="150">
<figcaption class="label">Placeholder 1</figcaption>
</figure>
<figure class="container">
<img alt="Placeholder" src="https://via.placeholder.com/150" width="150" height="150">
<figcaption class="label">Placeholder 2</figcaption>
</figure>
的建议尝试filter。
您可以使用一个或多个CSS过滤器。例如。 j08691;
filter: contrast(175%)
hue-rotate(90deg) sepia(100%) brightness(90%)
img:not([alt]) {
filter: opacity(25%);
}
据我所知,您将需要两件事来实现您想要的目标:
<img src="https://via.placeholder.com/150" width="150" height="150">
<img alt="Placeholder" src="https://via.placeholder.com/150" width="150" height="150">
的父元素,因此我们可以使用<img />
添加覆盖。对于此示例,我将使用:after
元素。这里是一个例子:
HTML
figure
CSS
<figure class="custom-figure">
<img src="https://via.placeholder.com/200x200" alt="">
</figure>
<figure class="custom-figure">
<img src="https://via.placeholder.com/200x200" alt="123">
</figure>
JS
.custom-figure{
display: inline-block;
margin: 10px;
}
.custom-figure--overlay{
position: relative;
}
.custom-figure--overlay:after{
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: linear-gradient(120deg, #eaee44, #33d0ff);
opacity: .7;
}
const addOverlayToEmptyAlt = () => {
const images = document.querySelectorAll(".custom-figure > img");
for (let each of images) {
const alt = each.getAttribute("alt").trim();
if (alt === "") {
each.closest(".custom-figure").classList.add("custom-figure--overlay");
}
}
};
addOverlayToEmptyAlt();