移动safari / chrome上的图像错误加载占位符图像问题

时间:2015-01-08 09:49:03

标签: jquery image function attr unbind

我正在使用以下脚本加载占位符图片,如果图片src png不可用/错误':

<script type="text/javascript">
jQuery("img").error(function () {
    jQuery(this).unbind("error").attr("src", "/images/people_placeholder.png");
});
</script>

我正在关闭</body>标记之前加载上述脚本。

它适用于Chrome桌面&amp;显示占位符图像。

它不适用于Safari桌面或Safari / Chrome中的手机

任何想法?

3 个答案:

答案 0 :(得分:4)

可能是因为如果onerror事件已经触发,则调用处理程序,您可以尝试捕获onerror事件,将此脚本放在</head>标记之前:

document.addEventListener('error', function (event) {
     var elm = event.target;
     if (elm.tagName == 'IMG') {
         elm.src = "/images/people_placeholder.png";
     }
 }, true ); // true to capture event

或尝试检查特定属性,您可以在</body>标记之前使用

jQuery("img").one('error', function () {
    jQuery(this).attr("src", "/images/people_placeholder.png"); //.unbind("error") is useless here
}).each(function () {
    if (this.complete && !this.naturalHeight && !this.naturalWidth) {
        $(this).triggerHandler('error');
    }
});

答案 1 :(得分:0)

试试这个

我在Link

找到了这个
function imgError(image) {
image.onerror = "";
image.src = "/images/people_placeholder.gif";
return true;
}

HTML:

<img src="image.png" onerror="imgError(this);"/>

答案 2 :(得分:0)

<img src="URL_OF_IMAGE" alt="image info" onerror="this.src='DEFAULT_IMG_URL'"/>

check docs

或创建全局函数来解决this issue