[英]How to prevent the display of image placeholder if the image is not found?
如果找不到圖像,有沒有辦法不顯示圖像占位符? 我已經通過自動饋送加載了圖像,對於某些項目,圖像在那里,但對於某些項目沒有。 所以,如果圖像不存在,我想顯示一個自定義占位符。
我在這里找到了答案
這段代碼效果很好!
function onImgErrorSmall(source)
{
source.src = "/images/no-image-100px.gif";
// disable onerror to prevent endless loop
source.onerror = "";
return true;
}
然后像這樣調用它:
<img src="/images/19013_small.jpg" alt="" onerror="onImgErrorSmall(this)" />
試試這個:
var tester=new Image()
tester.onload=function() {createPlaceHolderForImage(); }
tester.onerror=function() {handleError(); }
tester.src="http://www.temp.com/image.jpg"
如果圖像存在,則調用 onload 函數,否則調用 handleError
這是一個使用 jQuery 的示例,這也可以在 JavaScript 中完成:
<script type="text/javascript">
$(document).ready(function(){
$("img").each(function(){
var imgObj = $(this);
var img = new Image();
img.onerror=function(){ imgObj.attr('src','placeholder.gif'); }
img.src = imgObj.attr('src');
});
});
</script>
<ul>
<li><img src="blah.gif" /></li>
<li><img src="blah.png" /></li>
<li><img src="http://www.google.com/intl/en_com/images/srpr/logo2w.png" /></li>
</ul>
此代碼將遍歷每個圖像並檢查它是否存在。 如果它不存在,則將其替換為“placeholder.gif”圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.