How do you make a div “tabbable”?

后端 未结 4 1210
时光取名叫无心
时光取名叫无心 2020-12-14 13:46

I have buttons that are div elements and I want to make them so that it is possible for the user to press the tab key on their keyboard and move between them. I\'ve tried wr

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 14:29

    Make elements tabbable and clickable with key press using jquery

    Assumptions

    • All elements that are of a non-tabbable, non-clickable type and should be clickable have an onclick attribute (this could be changed to a class or other attribute)
    • All elements are of the same type; I will use divs.
    • You're using jquery

    Sample html:

    ...
    
    
    Button 1
    Button 2
    Button 3
    ...

    Jquery code: This is the code that will run when the page has loaded. It needs to run on your HTML page.

    $(()=>{
        // make divs with an onclick attribute tabbable/clickable
        $('div[onclick]')
            .attr('tabindex', '0')                     // Add tab indexes
            .keypress((evt)=>{
                var key = evt.key;
                evt.preventDefault();                  // Ensure all default keypress
                                                       // actions are not used
                if (key === ' ' || key === 'Enter') {  // Only send click events for Space
                                                       // or Enter keys
                    evt.currentTarget.click();         // Run the click event for element
                }
            });
    });
    

    You can find a working example here.

提交回复
热议问题