我有一个包含一堆图像的网页.有时图像不可用,因此在客户端的浏览器中显示损坏的图像.
如何使用jQuery获取图像集,将其过滤为损坏的图像然后替换src?
- 我认为使用jQuery更容易做到这一点,但结果却更容易使用纯粹的JavaScript解决方案,即Prestaul提供的解决方案.
好吧,让我们说你有这样的事情:
<span class="image" style="background-image: url('http://www.example.com/images/image1.png')"></span>
Run Code Online (Sandbox Code Playgroud)
我读过的每个CSS教程都涵盖了在背景图像代码之后使用背景颜色的概念,当然,当一个不可用时,它取代了图像,但......
如何指定备份背景图像 - 如果引用的图像不可用,应该显示该图像?如果没有CSS技巧,也许JavaScript可以处理它?
当所有其他浏览器(IE7,8,9,FF,Opera和Safari)都重复调用它时,为什么Chrome只调用img元素的onerror事件?
有没有办法强制它再次重复攻击(在Chrome中)?
HTML:
<div id="thisWorks">
this works in Chrome. onerror event is called once.
<img src="http://www.asdfjklasdfasdf.com/bogus1.png"
onerror="fixit(this);"
rsrc="http://eatfrenzy.com/images/success-tick.png" />
</div>
<div id="thisDoesNotWork">
this does not work in Chrome. onerror event is not called twice.
<img src="http://www.asdfjklasdfasdf.com/bogus1.png"
onerror="fixit(this);"
rsrc="http://www.asdfjklasdfasdf.com/bogus2.png|http://eatfrenzy.com/images/success-tick.png" />
</div>
Run Code Online (Sandbox Code Playgroud)
JAVASCRIPT:
function fixit(img)
{
var arrPhotos = img.getAttribute('rsrc').split('|');
// change the img src to the next available
img.setAttribute('src', arrPhotos.shift());
// now put back the image list (with one less) into the rsrc attr
img.setAttribute('rsrc', arrPhotos.join('|'));
return true;
}
Run Code Online (Sandbox Code Playgroud)
编辑: …
有没有一种方法可以告诉浏览器查看图像URL列表,直到找到可用的图像URL?纯HTML将是首选,但是我猜想JavaScript在这里可能是必要的(我已经在使用JQuery,所以这不是问题)。
编辑:感谢您的回答!我将添加一些说明:
我在image标签上有一个onerror处理程序,用于在找不到远程图像时处理切换.
问题是,对于某些破碎的远程图像,它不起作用.
http://a3.twimg.com/profile_images/522455109/calvin-and-hobbessm_normal.jpg
<img onerror="this.src='/images/pic_not_found.png'" src="http://a3.twimg.com/profile_images/522455109/calvin-and-hobbessm_normal.jpg">
Run Code Online (Sandbox Code Playgroud)
图片如下:1)找到远程图像时,2)未找到远程图像(未触发错误),3)未找到远程图像(触发错误)
html ×4
javascript ×3
image ×2
broken-image ×1
css ×1
events ×1
firefox ×1
jquery ×1
mime-types ×1
onerror ×1