2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!2018年的文章移至github上,点我去!

Fork me on GitHub

优雅的处理破裂图像

破裂图像


当我们img的src请求失败的时候,会触发img.error事件。这给我们提供了一个处理错误图片的时机,但是很显然这样的处理对我们来说太昂贵了。

于是图片就成了这样:

这样很显然比较难看。

优雅的处理


这时候给我们的图片添加下面一些CSS,立马就会和谐起来。

img {
        display: block;
        font-family: Helvetica, Arial, sans-serif;
        font-weight: 300;
        height: auto;
        line-height: 2;
        position: relative;
        text-align: center;
        width: 100%;
    }
    
    img:before {
        content: "We're sorry, the image below is broken :(";
        display: block;
        margin-bottom: 10px;
    }
    
    img:after {
        content: "(url: " attr(src) ")";
        display: block;
        font-size: 12px;
    }

替换原有的破裂图片


虽然上面已经相对优雅的处理了显示,但是那个默认的破裂图片确实很难看。这是我们不能忍受的,所以我们继续探寻。

img {
        display: block;
        font-family: Helvetica, Arial, sans-serif;
        font-weight: 300;
        height: auto;
        line-height: 2;
        position: relative;
        text-align: center;
        width: 100%;
    }
    
    img:after {
        content: "★" " " attr(alt);
        font-size: 16px;
        color: rgb(100, 100, 100);
        display: block;
        position: absolute;
        z-index: 2;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: #fff;
    }

我们将里面的破裂图片利用content进行了替换。是不是好看很多了!

参考:Styling Broken Images

posted on 2017-02-10 15:17  qize  阅读(1081)  评论(0编辑  收藏  举报

导航