Keyboard friendly CSS menus

2019-07-22 04:58发布

问题:

My Question is a sequel to this question

Keyboard accessible web dropdown menus?

While the above questions says that

We figured out how to show the menu with a keyboard shortcut, but I'm not sure how to select one of the entries

I have figured out how to select single menu items using accesskeys(and by underlining the key letter), but I do not know how to pop up a menu on keypress.

The menu is a XHTML/CSS only menu, XHTML being

<ul>
    <li>Menu 1
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </li>
    <li>Menu 2
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </li>
</ul>

回答1:

You can't.

Using accesskey will either activate or focus a link (depending on the browser).

Once a link has focus, you could get the menu to show up with something like:

ul#mainMenu > li > a:focus + ul { display: block }

But then you wouldn't be able to interact with anything inside the menu, as it would vanish as soon as the focus moved away.

CSS is a nice tool for describing presentation — which is what it is designed for — it is a very poor tool for describing interaction logic. JavaScript is designed for that, so use the right tool for the job.

The least problematic drop down menu script I've come across is UDM4 but I'd usually try to avoid drop downs entirely.



回答2:

Spudley: The reason focus isn't working like hover is that the hover action is assigned to the ul or li containing the link. The pop-up menu is a child inside of that ul/li so you are still hovering over an element inside of the ul/li. Focus can only be placed on keyboard interactive objects like links and form fields. This means when the link has focus you can show your menu using the CSS3 selector mentioned by Quentin, but the menu is not a child of the anchor tag, in order for it to be a child your sub menu would have to be inside of the a tag. This will as you might imagine cause problems with the links inside the sub menu. Try putting your hover tag on the a instead of the element inclosing the a and you will get the same results as the focus method.

Quentin: one reason I am currently looking into this is the combination of responsive design and accessibility. I have my menu at full screen size fully expanded, but when you shrink the screen the menu becomes a small button on the page that expands on hover/focus to save screen room on mobile/phone screens. I am also trying to avoid javascript and make it keyboard accessible as per accessibility requirements. I don't think there is a way to do it right now for the reason you listed. So my fall back is hide the menu and show using javascript and when it's not enabled always show the menu. Less user friendly for mobile users (with js disabled), but they can still access everything for accessibility requirements.