通常图片加载错误的回退方式都是通过监听img标签中的onerror事件,通过js来完成。但有时候某些特殊情况,需要用背景图片来代替img,这时候onerror就没有任何用处了。

其实我的想法很简单,如果一个背景图片加载不出来了,我就显示另一个背景图片就行了。所以,在同一个div上准备两个背景图不就行了。这个时候伪元素就很有用了。

.bg {
    background-image: url("./16.jpg");
    width: 300px;
    height: 300px;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    position: relative;
}
.bg::after {
    content: "图片正在加载中……";
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    left: 0; right: 0; top: 0; bottom: 0;
    z-index: -1;
}

bg

这里after可以使用另一个背景图,或者某些文字,或者其他动画效果。