html - 如果无法加载图像,则静默隐藏图标

标签 html css

在我正在处理的网站上,有一个菜单栏,其中包含几个选项,旁边有图标。这些图标纯粹是装饰性的,因此不需要替代文字。

不幸的是,图像有样式 - 设置的边距可以在 30 像素高的菜单栏中正确对齐它们。

这是按钮本身的代码(图标为 32x32 像素,但已调整为 16x16 像素):

<a class="button" href="#">
    <img src="images/crosshair.png" alt="">
    <span>Track and Trace</span>
</a>

CSS:

.button {
    display: block;
    padding: 3px 8px;
    background: #343434;
    text-decoration: none;
    color: #ececec;                     
    font-size: 0; // used by inline-block
}
.button img {
    display: inline-block;
    vertical-align: top; // needed to align the image properly; I couldn't find a better way.
    height: 16px;
    border: 0;
    font-size: 16px;
    margin: 4px 6px 4px 0;
}
.button span {
    display: inline-block;
    vertical-align: top;
    font-size: 16px;
}
.button:hover {
    background: #2E2E2E;
}

当图片没有加载时,这会因为边距而留下一个空间。

当图标无法加载时,其他人想要让图标完全消失时,他们会怎么做?

最佳答案

您可以使用“img”元素的“onerror”属性调用一个函数来设置 display: none 在外部“a”元素上。

参见 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img

关于html - 如果无法加载图像,则静默隐藏图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36112997/

相关文章:

jquery - 使嵌入式 PDF 在 iPad 中可滚动

javascript - 我应该使用 window.webkitRequestAnimationFrame 而不是 setInterval 吗?

css - 无法将我的布局居中

jquery - 如何在 Internet Explorer 中以倾斜 Angular 呈现 div

css - 如何将 div 单元格设置为像 th?

javascript - 查询 Ajax : Refreshing multiple divs with different id's

jquery - 如何去除网页上的滚动

javascript - JQuery 用选择值 No 来识别每个 Div

css - 选择箭头样式更改

HTML/CSS : IMG with height equal to the height of document (not the window)