PHP前端开发

确保图标链接的可访问性

百变鹏仔 3天前 #JavaScript
文章标签 图标

...通过一个小的客户端脚本自动实现

在此博客中,我逐渐告别图标字体,转而使用 svg 文件,我更喜欢使用背景图像进行集成,以保持灵活性。

在修改过程中,我注意到虽然我有时提供了带有标题的纯图标链接,但这些在可访问性方面并没有发挥任何作用。依赖屏幕阅读器的人还无法识别这些链接是什么。

有两种方法可以改变这个:aria-label 或添加文本并使其不可见。前者基本上只是一个拐杖,甚至没有得到所有浏览器的完全支持,因此只保留了不可见的文本。我在 grahamthedev 的 stack overflow 上找到了一个合适且非常有效的解决方案:

<a class="my-icon-link" title="my link">  <span class="visually-hidden">my link</span></a>
.my-icon-link {  background-image: url(/images/icons/my-icon.svg);}.visually-hidden {   border: 0;  padding: 0;  margin: 0;  position: absolute !important;  height: 1px;   width: 1px;  overflow: hidden;  clip: rect(1px 1px 1px 1px); /* ie6, ie7 - a 0 height clip, off to the bottom right of the visible 1px box */  clip: rect(1px, 1px, 1px, 1px); /*maybe deprecated but we need to support legacy browsers */  clip-path: inset(50%); /*modern browsers, clip-path works inwards from each corner*/  white-space: nowrap; /* added line to stop words getting smushed together (as they go onto seperate lines and some screen readers do not understand line feeds as a space */}

我现在的任务是用 span 扩展代码中的所有无文本图标链接...或者为此找到一个自动化,因为所有这些链接都已经有一个标题,而它正是需要转移到链接的内容文本。 由于通过 javascript 注入文本时可访问性不会受到损害,因此我找到了以下客户端解决方案,它通过脚本嵌入到每个页面的页脚中:

function ensureIconLinkText() {  let linksWithoutText = document.querySelectorAll("a[href^='http']:empty");  linksWithoutText.forEach(e =&gt; {    if (window.getComputedStyle(e).display !== "none") {      if (e.title) {        let eText = document.createElement("span");        eText.innerText = e.title;        eText.classList.add("visually-hidden");        e.append(eText);      } else {        console.error("Link without Text and Title: " + e.outerHTML);      }    }  });}ensureIconLinkText();

文字形式的代码:
找到所有不带文本的 a 标签,遍历它们,如果该元素不是故意隐藏的,并且定义了标题,则使用其文本值创建一个新的 span 标签并将其插入链接中,否则在控制台中输出错误

通过这种方法,我可以保留链接不变,并且可以在控制台中查看我是否忘记了某处的标题。