求助::focus-within无法实现类似hover的导航栏交互效果
Let's get your :focus-within implementation working! The issue here boils down to understanding exactly how :focus-within triggers, and adjusting your selectors to mirror your hover behavior for keyboard navigation scenarios.
Why Your Initial Attempt Might Have Failed
:focus-within activates when the element itself or any of its descendants has focus. In your nav setup, the only natively focusable elements are the <a> tags inside each <li>. So we need to target the nav when its child links gain focus, then adjust the opacity of list items accordingly.
Working Solution Code
Here's the updated HTML and CSS that replicates your hover effect using :focus-within, while keeping your original hover behavior intact:
<nav> <ul> <li><a href="#">Item Number 1</a></li> <li><a href="#">Item Number 2</a></li> <li><a href="#">Item Number 3</a></li> <li><a href="#">Item Number 4</a></li> </ul> </nav>
/* Original hover effect (kept intact) */ nav:hover ul li { opacity: 0.4; } nav ul li:hover { opacity: 1; } /* New focus-within effect for keyboard navigation */ nav:focus-within ul li { opacity: 0.4; } nav ul li:focus-within { opacity: 1; } /* Base styles (your existing styles) */ nav ul li { line-height: 1.5; } body { margin: 5rem; }
How This Works
nav:focus-within ul li: When any descendant of<nav>(i.e., any of the<a>tags) receives focus, we set all<li>elements to 40% opacity.nav ul li:focus-within: When an<li>contains a focused element (the<a>inside it), we override the opacity to 100% for that specific list item.
Accessibility Note
For better usability, keep the default focus ring on the <a> tags, or customize it to match your design. Never remove focus indicators entirely—they're critical for keyboard-only users!
内容的提问来源于stack exchange,提问作者nick

