解決js圖片載入時出現404的問題_javascript技巧
經營網站久了之後,無法避免會出現圖片404的情況,原因可能是圖片檔案本來就不存在或目前不存在。常見的解決方案是將404圖片隱藏或是替換為預設的圖片。
img標籤事件屬性
img標籤可使用的時間屬性有:
onabort, onbeforeunload, onblur, onchange, onclick, oncontextmenu, ondblclick, ondrag, ondragend, ondragenter, ondragleave, ondragover, ondconn, ondrop, on, . mousedown, 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"); }
注意:需要將處理函數定義在head,防止圖片載入出錯時沒有讀取到處理函數
2. 使用jQuery監聽error
// 通常不会再HTML里面内联js,可以使用.error对图片进行监听处理 $('#test img').error(function() { $(this).hide(); // $(this).attr("src", "images/demo.png"); });
注意:jQuery載入需要在img前,處理函數需在img後
3. 使用函數處理
// 原生JS解决方案 function $id(id) { return !id || id.nodeType === 1 ? id : document.getElementById(id); } function isType(o, t) { return (typeof o).indexOf(t.charAt(0).toLowerCase()) === 0; } // 主要逻辑 function image(src, cfg) { var img, prop, target; cfg = cfg || (isType(src, 'o') ? src : {}); img = $id(src); if (img) { src = cfg.src || img.src; } else { img = document.createElement('img'); src = src || cfg.src; } if (!src) { return null; } prop = isType(img.naturalWidth,'u') ? 'width' : 'naturalWidth'; img.alt = cfg.alt || img.alt; // Add the image and insert if requested (must be on DOM to load or // pull from cache) img.src = src; target = $id(cfg.target); if (target) { target.insertBefore(img, $id(cfg.insertBefore) || null); } // Loaded? if (img.complete) { if (img[prop]) { if (isType(cfg.success,'f')) { cfg.success.call(img); } } else { if (isType(cfg.failure,'f')) { cfg.failure.call(img); } } } else { if (isType(cfg.success,'f')) { img.onload = cfg.success; } if (isType(cfg.failure,'f')) { img.onerror = cfg.failure; } } return img; }
以上函數有許多用途:
1. 取得圖片資訊:圖片是否可下載,圖片寬高
image('img',{ success : function () { alert(this.width + "-" + this.height); }, failure : function () { alert('image 404!'); }, }); // 验证资源是否下载 image('images/banner/banner_2.jpg', { success : function () {console.log('sucess')}, failure : function () {console.log('failure')}, target : 'myContainerId', insertBefore : 'someChildOfmyContainerId' });
2. 下載並插入圖片
var report = $id('report'), callback = { success : function () { report.innerHTML += '<p>Success - ' + this.src + ' ('+this.offsetWidth+'x'+this.offsetHeight+')</p>'; }, failure : function () { report.innerHTML += '<p>Failure - ' + this.src + ' ('+this.offsetWidth+'x'+this.offsetHeight+')</p>'; }, target : 'target' }; image('img', callback); image('images/banner/banner_2.jpg', callback);
以上就是js針對圖片載入時出現404問題的解決方法,希望大家有所收穫。

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題











Python和JavaScript開發者的薪資沒有絕對的高低,具體取決於技能和行業需求。 1.Python在數據科學和機器學習領域可能薪資更高。 2.JavaScript在前端和全棧開發中需求大,薪資也可觀。 3.影響因素包括經驗、地理位置、公司規模和特定技能。

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

如何在JavaScript中將具有相同ID的數組元素合併到一個對像中?在處理數據時,我們常常會遇到需要將具有相同ID�...

實現視差滾動和元素動畫效果的探討本文將探討如何實現類似資生堂官網(https://www.shiseido.co.jp/sb/wonderland/)中�...

學習JavaScript不難,但有挑戰。 1)理解基礎概念如變量、數據類型、函數等。 2)掌握異步編程,通過事件循環實現。 3)使用DOM操作和Promise處理異步請求。 4)避免常見錯誤,使用調試技巧。 5)優化性能,遵循最佳實踐。

深入探討console.log輸出差異的根源本文將分析一段代碼中console.log函數輸出結果的差異,並解釋其背後的原因。 �...

探索前端中類似VSCode的面板拖拽調整功能的實現在前端開發中,如何實現類似於VSCode...
