如果图像 src png 不可用/出现错误,我将使用以下脚本加载占位符图像:
<script type="text/javascript">
jQuery("img").error(function () {
jQuery(this).unbind("error").attr("src", "/images/people_placeholder.png");
});
</script>
我正在关闭之前加载上述脚本 </body>
标签。
它在 Chrome 桌面上运行良好并显示占位符图像。
它不适用于 Safari 桌面版或手机上的 Safari/Chrome
有什么想法吗?
最佳答案
这可能是因为如果 onerror
则未调用处理程序事件已触发,您可以 try catch 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');
}
});
关于jquery - 移动 safari/chrome 上的图像错误加载占位符图像问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27837134/