辅助功能:使用媒体查询隐藏文本

Rún*_*erg 5 html css accessibility

制作不可见内容的当前方法(即在屏幕上隐藏文本,但可将其提供给屏幕阅读器)似乎颇为棘手。目前,引导程序具有一个sr-only定义为的mixin:

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:使用仅屏幕的简单媒体查询是否可以更轻松地完成此操作?我特别想知道是否可以接受以下媒体查询和规则进行隐藏(例如,以下应用中的标题):

@media only screen {
  h2 {
    display: none;
  }
}
Run Code Online (Sandbox Code Playgroud)

换句话说:媒体查询是否@media only screen适用于屏幕阅读器和屏幕?

扩展此代码段,以查看可能有用的地方。

const sections = document.querySelectorAll('section');
const anchors = document.querySelectorAll('nav a');

window.addEventListener('hashchange', ({ newURL }) => {
  const { hash } = new URL(newURL);
  
  sections.forEach(section => {
    if (section.matches(hash)) {
      section.style.display = null;
    } else {
      section.style.display = 'none'
    }
  });
  
  anchors.forEach(anchor => {
    if (anchor.href === newURL) {
      anchor.parentNode.classList.add('active');
    } else {
      anchor.parentNode.classList.remove('active');
    }
  });
});
Run Code Online (Sandbox Code Playgroud)
article {
  display: flex;
}

section {
  flex-basis: 50%;
  max-height: 100vh;
  overflow: auto;
}

nav {
  margin-right: 1em;
}

nav a {
  color: #adadad;
}

nav .active a {
  color: #333333;
  font-weight: bold;
}

@media only screen {
  h2 {
    display: none;
  }
}
Run Code Online (Sandbox Code Playgroud)
<article>
  <nav>
    <ol>
      <li class="active">
        <a href="#chapter-1">Chapter 1</a>
      </li>

      <li>
        <a href="#chapter-2">Chapter 2</a>
      </li>

      <li>
        <a href="#chapter-3">Chapter 3</a>
      </li>
    </ol>
  </nav>

  <section id="chapter-1">
    <h2>Chapter 1</h2>
    <p>The heading above is redundant for sighted users.</p>
  </section>
  
  <section id="chapter-2" style="display: none;">
    <h2>Chapter 2</h2>
    <p>They can infer it from the nav bar to the left.</p>
  </section>
  
  <section id="chapter-3" style="display: none;">
    <h2>Chapter 3</h2>
    <p>But screen readers might benefit from having it there.</p>
  </section>
</article>
Run Code Online (Sandbox Code Playgroud)

slu*_*ous 5

我不知道这是否不太“ hacky”,但是肯定要简单一些。如果某个元素被aria-labelledby或引用,aria-describedby并且该元素被隐藏,则仍将在可访问名称计算中使用该元素。

因此sr-only,您可以真正地隐藏它,而不是使用类来隐藏文本。

<span id="foo" style="display:none;">you can't see me</span>
...
<a href="#" id="myself" aria-labelledby="myself foo">hello</a>
Run Code Online (Sandbox Code Playgroud)

当您导航到该链接时,屏幕阅读器会说:“您好,您看不到我”