運營網站久了之后,無法避免會出現圖片404的情況,原因可能是圖片文件本來就不存在或目前不存在。常見的解決方案是將404圖片隱藏或者是替換為默認的圖片。
img標簽事件屬性
img標簽可使用的時間屬性有:
onabort, onbeforeunload, onblur, onchange, onclick, oncontextmenu, ondblclick, ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop, onerror, onfocus, onkeydown, onkeypress, onkeyup, onload, onmessage, onmousedown, onmousemove, onmouseover, onmouseout, onmouseup, onmousewheel, onresize, onscroll, onselect, onsubmit, onunload
img標簽常用的事件如下:
onerror:圖像加載過程中發生錯誤時被觸發。
onabort:圖片加載的時候,用戶通過點擊停止加載時觸發,通常在這里觸發一個提示:“圖片正在加載”。
onload:當圖片加載完成之后觸發。
1. 對圖片監聽onerror事件
- <img src="someimage.png" onerror="imgError(this);" />
- // 原生JS:
- function imgError(image){
- // 隱藏圖片
- image.style.display = 'none';
- // 替換為默認圖片
- // document.getElementById("img").setAttribute("src", "images/demo.png");
- }
- // 使用jQuery處理:
- function imgError(image){
- $(image).hide();
- // $(this).attr("src", "images/demo.png");
- }
新聞熱點
疑難解答
圖片精選