我想给损坏/错误的图像一些额外的 CSS:
img:error {
max-width: 20px;
max-height: 20px;
}
但这不起作用。有没有办法用纯 CSS 来做到这一点?是否有一个img
伪选择器?甚至更好:一个有效的肮脏黑客?
我环顾四周,但似乎没有人想知道=)
(是的,我知道 JS 可以做到,我也知道怎么做;不用提了。)
我想给损坏/错误的图像一些额外的 CSS:
img:error {
max-width: 20px;
max-height: 20px;
}
但这不起作用。有没有办法用纯 CSS 来做到这一点?是否有一个img
伪选择器?甚至更好:一个有效的肮脏黑客?
我环顾四周,但似乎没有人想知道=)
(是的,我知道 JS 可以做到,我也知道怎么做;不用提了。)
There is no way in CSS specs or drafts, but Firefox has a proprietary selector (pseudo-class) :-moz-broken
. Its documentation is very concise and it says “intended for use mainly by theme developers”, but it can be used e.g. as follows:
:-moz-broken { outline: solid red }
:-moz-broken:after { content: " (broken image)" }
Although the documentation says that it “matches elements representing broken image links”, it actually matches broken images (an img
element where the src
attribute does not refer to an image), whether they are links or not. Presumably, “links” really means “references” here.
CSS 2.1 says: “This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.” But Selectors Level 3 (CSS3 Selectors) just says about them: “They are explained in CSS 2.1.” In practice, browsers handle them differently. Oddly enough, Firefox supports :-moz-broken:after
but ignores :-moz-broken:before
. It does not support either of these pseudo-elements for normal images, but img:after
, too, is supported for a broken image (i.e., the specified content appears after the alt
attribute value).
为此,您应该使用 alt 属性,如果链接断开,它会显示出来,并且您也可以设置图像的背景样式:例如:
img {
display:inline-block;
vertical-align:top;
min-height:50px;
min-width:300px;
line-height:50px;
text-align:center;
background:
linear-gradient(to bottom,
blue,
orange,
green);
font-size:2em;
box-shadow:inset 0 0 0 3px;
}
显示图像时,这些样式将被隐藏。 http://codepen.io/anon/pen/Kxipq 如您所见,我们不检查损坏的链接,但提供替代方案,对盲人、搜索引擎等有用,以及一些额外的样式完成它:)
一些额外的图像 alt 属性最佳实践
NO 没有 :error 伪类。这是一个很好的网站,可以查看可用内容的完整列表:
http://reference.sitepoint.com/css/css3psuedoclasses
2015 年 7 月 编辑/添加:(
谢谢Rudie)
https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
<img src="not_found_image.png" onerror='this.style.display = "none"' />
来自: https ://www.geeksforgeeks.org/how-to-hide-image-not-found-icon-when-source-image-is-not-found/