use*_*484 2 jquery image function unbind attr
如果图像 src png 不可用/错误,我将使用以下脚本加载占位符图像:
<script type="text/javascript">
jQuery("img").error(function () {
jQuery(this).unbind("error").attr("src", "/images/people_placeholder.png");
});
</script>
Run Code Online (Sandbox Code Playgroud)
我正在关闭</body>标签之前加载上述脚本。
它在 Chrome 桌面上运行良好并显示占位符图像。
它不适用于 Safari 桌面版或手机的 Safari/Chrome
有任何想法吗?
这可能是因为如果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
Run Code Online (Sandbox Code Playgroud)
或者尝试检查特定属性,您可以在</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');
}
});
Run Code Online (Sandbox Code Playgroud)