正确的方式显示下拉焦点与CSS [英] Proper way to show drop down on focus with CSS

查看:112
本文介绍了正确的方式显示下拉焦点与CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图制作一个键盘可访问的菜单,但我无法弄清楚如何让它显示焦点上的下拉菜单。



我有

  .main-menu li:hover ul,
.main-menu li:focus ul {
显示:块;

$ / code>

问题在于,当它专注于嵌套在李并没有显示ul。 Tabbing着重于一个标签。



以下是我的完整代码: http://jsfiddle.net/bxpe4/

解决方案

标签时,您将 anchor 内部 .main-menu li ,而不是 list-item 本身。

有两种解决方法:a)使用 + code> selector

  .main-menu li a:focus + ul {
display :block;
}

然而,这会让其他锚点出现问题它应该到子菜单中的第一个锚,但它没有显示,所以什么也没有发生)。

使用 tabindex code> property



这将要求您在菜单锚点上将 tabindex 设置为负数值(将它们从标签中移除)并将标签设置为列表项。

请参阅使用tabindex演示



您需要更改锚点和列表项目的样式以显示红色背景,添加新的选择器:

  .main-menu li a:hover,
.main-menu li a:focus,
.main-menu li.dropped> a,
.main-menu li:focus> a / *添加了* / {
/ *您的款式* /
}

然而,这并不是一个很好的做法,因为重点列表项意味着你不能使用键盘访问锚点。您可以使用JavaScript来模拟事件(绑定列表项的按键以点击锚点),在jQuery中它可能是这样的:

 ('key',function(){
$(this).find('a')。click();
($ li'tabindex' });

参见使用tabindex进行事件模拟演示



如果顶级锚点没有任何操作(仅用于对于下拉紫袍),在这种情况下,你根本不需要它们。


I'm trying to make a keyboard accessible menu but I can't figure out how to get it to show the the drop down on focus.

I have

.main-menu li:hover ul,
.main-menu li:focus ul {
    display: block;
}

The issue is that when its focusing its focusing on the a that's nested in the li and not showing the ul. Tabbing is focusing on the a tags.

Here is my full code: http://jsfiddle.net/bxpe4/

解决方案

When tabbing, you focus the anchor inside .main-menu li, not the list-item itself.

There are two workarounds:

a) using + selector

.main-menu li a:focus + ul {
    display: block;
}

However, that makes it problematic to tab to other anchors (on tabs press, it should go to the first anchor in submenu, but it gets undisplayed, so nothing happens).

b) using tabindex property

That would require you to set tabindex on menu anchors to negative value (remove them from tabbing) and set tabbing to list-items.

see Using tabindex demo

You would need to change the styling of anchors and list-items to show the red background too, adding a new selector:

.main-menu li a:hover,
.main-menu li a:focus,
.main-menu li.dropped > a,
.main-menu li:focus > a /* this one was added */ {
    /* your styles */
}

This however, is not really a good practice as focused list-items mean, that you can't access the anchor using keyboard. You could use JavaScript to simulate the event (bind keypress of the list-item to click on the anchor), in jQuery it would be something like this:

$('li[tabindex]').on('keypress', function() {
    $(this).find('a').click();
});

see Using tabindex with event simulation demo

This is not an issue if the top-level anchors don't have any action (are only used for drop down purpouses), in which case you wouldn't need them at all.

这篇关于正确的方式显示下拉焦点与CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆