块编辑器开发文档

💡 云策文档标注

概述

VisuallyHidden 是一个 WordPress 组件,用于渲染视觉上隐藏但可供屏幕阅读器等辅助设备访问的文本内容。它通过绝对定位实现隐藏效果,但需注意其可能影响布局的副作用。

关键要点

  • VisuallyHidden 组件用于隐藏视觉内容,同时保持对屏幕阅读器的可访问性。
  • 组件渲染的元素具有 position: absolute 样式,可能影响堆叠上下文和布局,例如导致意外滚动条。
  • 建议在 VisuallyHidden 的直接父元素上添加 position: relative 来创建堆叠上下文,以避免布局问题。

代码示例

import { VisuallyHidden } from '@wordpress/components';

function Example() {
    return (
        <VisuallyHidden>
            <label>Code is Poetry</label>
        </VisuallyHidden>
    );
}

注意事项

  • VisuallyHidden 可能忽略祖先元素的 overflow 样式,因为它采用其堆叠上下文的 overflow。
  • 在直接父元素上添加 position: relative 是解决意外滚动条等问题的常见方法。

📄 原文内容

VisuallyHidden is a component used to render text intended to be visually hidden, but will show for alternate devices, for example a screen reader.

Usage

import { VisuallyHidden } from '@wordpress/components';

function Example() {
    return (
        <VisuallyHidden>
            <label>Code is Poetry</label>
        </VisuallyHidden>
    );
}

Best practices

The element that VisuallyHidden renders has the style position: absolute. When using this component be careful of the stacking context. Even though VisuallyHidden isn’t visible, it can still affect layout. An example of this is that VisuallyHidden may ignore overflow styles of ancestor elements because it instead adopts the overflow of its stacking context. One known side-effect can be an unexpected scrollbar appearing. To fix this kind of issue, introduce a stacking context on a more immediate parent of VisuallyHidden. Adding position: relative is often an easy way to do this.