如果没有找到图像,如何防止显示图像占位符

How to prevent the display of image placeholder if the image is not found?

本文关键字:图像 显示 显示图 占位符 何防止 如果没有      更新时间:2023-09-26

如果没有找到图像,是否有办法不显示图像占位符?我已经通过自动馈送加载了图像,并且对于一些项目图像在那里,但对于一些没有。因此,如果图像不在那里,我想显示一个自定义占位符。

我在这里找到了答案

这段代码工作得很好!

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)" />

try 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'图像。