Use: focus as a: keyboard hover replacement

WCAG 2.0 also recommends using :focus when :hover used for link elements to support keyboard navigation. This works well for link elements, but there are several differences between them.

  • any element can have a state :hover , but only very little can be focused
  • When you hover over an element, you also hover over all of its parent elements. This does not apply to focus.

This question is strictly about css. Is there a way to simulate :hover behavior (as described above) to navigate the keyboard? Or are there any good reasons why you would not want to?

To make this clearer, an example is provided:

HTML:

 <div id="box"> foo bar <a href="#">click me</a> </div> 

CSS

 #box { opacity: 0.3; } #box:hover { opacity: 1; } #box a:focus { opacity: 1; } 

When using the mouse, I will hover over the link element before using it. Since the state :hover extends upwards, #box will be completely opaque.

When using the keyboard, I will focus the link element before using it. Since the :focus state does not extend upwards, #box will not be fully opaque.

+7
css accessibility hover
source share
2 answers

This can be done in JavaScript using focusin / focusout (they are similar to focus and blur , except that they bubble). Here is the violin.

It comes down to this function:

 var deepFocus = function(element, cls) { cls = cls || 'deep-focus'; element .on('focusin', function() { element.addClass(cls); }) .on('focusout', function() { var value = !!element.find(':focus').length; element.toggleClass(cls, value); }); }; 

Update . There is a project specification that contains a :focus-within selector that will exactly do what is required here.

+1
source share

Make: the effect of focusing on the elements does not bind and form the elements you need in the tabindex attributes. when you put it on each element, you can assign an element to it: focus pesudo.

in your example, you need to understand that the opacity remains on the parent div when the opacity of the link changes.

You can see the working sample here . or sample for using tabindex

 <div tabindex="1">Touch the Div</div> 
0
source share

All Articles