Skip to Content
文档

焦点环

如何在 Chakra UI 中设置焦点状态的样式

焦点环用于标识页面上当前获得焦点的元素。虽然这对于可访问性很重要,但为每个组件设置一个焦点环样式可能会很繁琐。

¥The focus ring is used to identify the currently focused element on your page. While this is important for accessibility, styling every component to have a focus ring can be tedious.

Chakra UI 提供 focusRingfocusVisibleRing 样式属性,可轻松设置对焦环的样式。focusRing 属性的值可以是 "outside"、"里面" 或 "mixed"。

¥Chakra UI provides the focusRing and focusVisibleRing style props to style focus ring with ease. The value of the focusRing prop can be "outside", "inside", or "mixed".

焦点环

¥Focus Ring

此焦点环映射到 &:is(:focus, [data-focus]) CSS 选择器。

¥This focus ring maps to the &:is(:focus, [data-focus]) CSS selector.

以下是如何从零开始使用焦点环设置按钮样式:

¥Here's how to style a button from scratch with a focus ring:

<chakra.button px="4" py="2" focusRing="outside">
  Click me
</chakra.button>

焦点可见环

¥Focus Visible Ring

此焦点环映射到 &:is(:focus-visible, [data-focus-visible]) CSS 选择器。

¥This focus ring maps to the &:is(:focus-visible, [data-focus-visible]) CSS selector.

<chakra.button px="4" py="2" focusVisibleRing="outside">
  Click me
</chakra.button>

焦点环和焦点可见之间的差异环

¥Difference between Focus Ring and Focus Visible Ring

Focus Visible Ring 的功能与 Focus Ring 类似,但有一个关键区别:它仅在元素获得键盘焦点时应用焦点指示器样式。

¥The Focus Visible Ring functions similarly to the Focus Ring, but with a key difference: it only applies focus indicator styles when an element receives keyboard focus.

这确保了焦点环仅在通过键盘导航时可见,从而提高了可访问性,而不会影响鼠标交互。

¥This ensures that the focus ring is visible only when navigating via keyboard, improving accessibility without affecting mouse interactions.

内置对焦环

¥Built-in Focus Ring

以下是支持的焦点环预览。

¥Here's a preview of the supported focus ring.

inside
outside
mixed

自定义

¥Customization

环颜色

¥Ring Color

要更改特定组件的焦点环颜色,可以使用 focusRingColor 属性。

¥To change the focus ring color for a specific component, you can use the focusRingColor prop.

<Button focusRingColor="red.500">Click me</Button>

要全局更改焦点环的颜色,可以配置 focusRing 语义标记。

¥To change the color of the focus ring globally, you can configure the focusRing semantic token.

const colors = defineSemanticTokens.colors({
  focusRing: {
    value: { base: "{colors.red.500}", _dark: "{colors.red.500}" },
  },
})

环宽度

¥Ring Width

要更改特定组件的焦点环宽度,可以使用 focusRingWidth 属性。

¥To change the focus ring width for a specific component, you can use the focusRingWidth prop.

<Button focusRingWidth="2px">Click me</Button>

环样式

¥Ring Style

要更改特定组件的焦点环样式,可以使用 focusRingStyle 属性。

¥To change the focus ring style for a specific component, you can use the focusRingStyle prop.

<Button focusRingStyle="dashed">Click me</Button>

Previous

动画样式

Next

背景