图片加载失败解决方案

4,933 阅读2分钟

这是我参与新手入门的第二篇文章,有的时候因为网络问题或者链接问题导致图片无法正产加载显示,为<img>标签添加alt属性浏览器会帮你解决无法正常查看图片但是能显示一段文字让你知道图片中的一个大概的信息。我修改了图片的链接让图片无法正常加载,当然不同的浏览器有不同的解决方案,如图(图一:Edge、图二:火狐):

1.微信截图_20210708121242.png 2.微信截图_20210708121401.png

我们可以看到浏览器会帮我们处理这一问题,但是处理的效果不是非常了完美,会影响页面的布局。如果是放在一条新闻内显示,我们可以看出效果并不是很好,整体显得非常的空旷。

微信截图_20210708145920.png

微信截图_20210708145856.png

这里有一个onerror属性,它会在图片加载失败的时候执行JavaScript,有了这个属性我们基本就有了思路了。首先我们可以创建一个类名,当图片加载失败的时候我们给图片添加刚刚创建的类名,在通过类名的伪类为图片添加一个加载失败的图片,光说没用现在我们来看代码和效果吧。

<img src="img/shisui1.jpg" alt="止水" onerror="this.classList.add('wutu')">
.wutu {
    display: block;
    position: relative;
    width: 100%;
    height: 100%;
}
.wutu::before {
    position: absolute;
    top: 0;
    left: 0;
    content: '';
    display: block;
    width: 100%;
    height: 100%;
    background: url('./img/wutu.png') no-repeat center center #ccc;
    background-size: contain;
}

微信截图_20210708145940.png

可以看到我们的加载失败的图片已经显示出来了,但是图片加载失败的文字被覆盖掉了,所以我们可以使用另外一个伪类通过content: attr(alt)给他显示出来。

下图就是最终的效果:

微信截图_20210708151158.png

最终代码:

<div class="card">
    <div class="img">
        <img src="img/shisui1.jpg" alt="止水" onerror="this.classList.add('wutu')">
    </div>
    <h3>瞬身止水</h3>
    <p>火之国木叶隐村宇智波一族的天才忍者。</p>
</div>
.card {
    width: 380px;
    border: 1px solid gray;
    border-radius: 5px;
    padding: 5px;
}
.card .img {
    height: 260px;
    overflow: hidden;
}
.card .img img {
    width: 100%;
    object-fit: cover;
}
.wutu {
    display: block;
    position: relative;
    width: 100%;
    height: 100%;
}
.wutu::before {
    position: absolute;
    top: 0;
    left: 0;
    content: '';
    display: block;
    width: 100%;
    height: 100%;
    background: url('./img/wutu.png') no-repeat center center #ccc;
    background-size: contain;
}
.wutu::after {
    position: absolute;
    content: attr(alt);
    left: 0;
    bottom: 0;
    width: 100%;
    font-size: 17px;
    height: 1.5rem;
    line-height: 1.5rem;
    text-align: center;
    background: gray;
    color: #fff;
    z-index: 1;
}