使用字体图标作为替代文本<img>



我有一些图像在 DOM 准备就绪后加载了一个便宜的技巧:

<img src="" data-src="/path/to/img" alt="">

我只是使用 JS 将data-src的内容放入 src 属性中。没什么好看的。
但是由于有几百张图像要加载,这需要一些时间。所以我试图使用 FontAwesome 图标的 unicode 作为替代文本来显示一个齿轮作为占位符:

<img src="" data-src="/path/to/img" alt="&#xf013;">

不幸的是,这不起作用,因为整个FontAwesome-magic没有点击。
有没有人尝试过同样的方法?这到底可能吗?

我不能声称这个解决方案的功劳,它属于写了解决@Stephan_Weinhold问题的评论@PeeHaa。

我只是想创造清晰度,因为所有的官方答案都使用JavaScript,只有当你阅读评论时,你才会发现使用简单的HTML/CSS是可能的。

.HTML

<img src="" data-src="/path/to/img" alt="&#xf007;" class="passphoto">

.CSS

img.passphoto { 
    font-family: 'Font Awesome 5 Free';
    /* customize the following as desired */
    font-size: 9em;
    display: inline-block;
    width: 200px;
    height: 234px;
    border: 1px solid lightgray;
}

恐怕你不能。但我可以给你一个技巧。

诀窍是你可以处理图像加载错误(这就是为什么你想要替代文本,不是吗?),然后显示你想要的图标。

这不是

SEO的好解决方案,但您想显示一个图标,所以我想这不是您的目标。

注意 如果您在代码段中看不到效果,请在垃圾箱中观看它 - 我认为这是因为缓存问题。

$('img').bind('error', function() {
  console.log('error');
  $(this).hide().after('<i class="fa fa-gear"></i>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<img src="blablalba" />

http://jsbin.com/kahuxaqezu/1/edit?html,js,output

我现在

在iPhone上遇到了问题?

如果找不到图像,我使用 ONERROR 注入 CLASS

.CSS

/* FONT AWESOME (support for all icons) */
.icon::before {
  display: inline-block;
  font-style: normal;
  font-variant: normal;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
}
/* FONT AWESOME (user icon) */
.fa_user:after {
    font-family: 'Font Awesome 5 Free';
    font-size: 9em !important;              /* added !important, couldn't use 900, didn't work */
    content: "f2bd";                       /* UNICODE (Font Awesome) <i class="far fa-user-circle"></i> */
    line-height: 1.0;                       /* I had to add this because it was INHERITING 1.5 throwing off the spacing */
}

.HTML

<img src="./images/.photo.jpg" onerror="this.classList.add('icon', 'fa_user');" alt=''>

字体真棒文档

用户图标

最新更新