我想聚焦div
周围的按钮,但只有当键盘聚焦时。通常focus-within
有效,但在这种情况下,它应该仅关注键盘焦点 ( focus-visible:
),而不是在使用鼠标单击时 ( focus:
)。
本质上,我需要结合focus-within
和focus-visible
。如何才能做到这一点?
顺风游戏:https://play.tailwindcss.com/ApDB5gSjqv
<div class="flex h-screen items-center justify-center">
<div class="rounded-lg bg-green-100 px-20 py-20 focus-within:ring-4 focus-within:ring-blue-300">
<button class="bg-green-200 px-6 py-3 focus:outline-none">Focusable Button</button>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
笔记:
你确实可以使用:has
with:focus-visible
来实现你想要的。检查caniuse上的浏览器支持。
使用任意变体来构建选择器:
<div class="[&:has(:focus-visible)]:ring-4">
<button>Focusable button</button>
</div>
Run Code Online (Sandbox Code Playgroud)