破裂圖像 當我們img的src請求失敗的時候,會觸發 事件。這給我們提供了一個處理錯誤圖片的時機,但是很顯然這樣的處理對我們來說太昂貴了。 於是圖片就成了這樣: 這樣很顯然比較難看。 優雅的處理 這時候給我們的圖片添加下麵一些CSS,立馬就會和諧起來。 替換原有的破裂圖片 雖然上面已經相對優雅的處理 ...
破裂圖像
當我們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進行了替換。是不是好看很多了!