繁体   English   中英

如果找不到图像,如何防止显示图像占位符?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM