gpt4 book ai didi

javascript - 不用 jQuery 处理丢失的图像

转载 作者:行者123 更新时间:2023-11-28 03:15:33 30 4
gpt4 key购买 nike

我想创建一个干净的解决方案来处理客户端丢失的图像

使用 <img src="image.gif" onerror="handleErrors()">

到目前为止,handleErrors 看起来像这样:

function handleErrors() {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}

但我觉得这不够可扩展,屏幕阅读器也无法访问无图像。

对于这个问题,什么是更具可扩展性和可访问性的解决方案?

最佳答案

尝试为您的图片使用替代文本属性。

They are more accessible for screen readers.

Also you can create a module which on error hides the images and replaces them with their alt text

这是我为处理此类问题而编写的模块:

function missingImagesHandler() {
var self = this;
// get all images on the page
self.pageImages = document.querySelectorAll("img");
self.ImageErrorHandler = function (event) {
// hide them
event.target.style.display = 'none';
// replace them with alt text
self.replaceAltTextWithImage(event.target);
}
self.replaceAltTextWithImage = function (imageElement) {
var altText = imageElement.getAttribute("alt");
if (altText) {
var missingLabel = document.createElement("P");
var textnode = document.createTextNode(altText);
missingLabel.appendChild(textnode)
imageElement.parentNode.insertBefore(missingLabel, imageElement);
} else {
console.error(imageElement, "is missing alt text");
}
}
self.attachErrorHandler = function () {
self.pageImages.forEach(function (img) {
img.addEventListener("error", self.ImageErrorHandler);
});
}
self.init = function () {
// NodeList doesn't have forEach by default
NodeList.prototype.forEach = Array.prototype.forEach;
self.attachErrorHandler();
}
return {
init: self.init
}
}
var ImgHandler = new missingImagesHandler();
ImgHandler.init();

关于javascript - 不用 jQuery 处理丢失的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28234698/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com