How to keep focus within modal dialog?

后端 未结 9 921
醉酒成梦
醉酒成梦 2020-12-17 17:29

I\'m developing an app with Angular and Semantic-UI. The app should be accessible, this means it should be compliant with WCAG 2.0. To reach this p

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 18:11

    Here's my solution. It traps Tab or Shift+Tab as necessary on first/last element of modal dialog (in my case found with role="dialog"). Eligible elements being checked are all visible input controls whose HTML may be input,select,textarea,button.

    $(document).on('keydown', function(e) {
        var target = e.target;
        var shiftPressed = e.shiftKey;
        // If TAB key pressed
        if (e.keyCode == 9) {
            // If inside a Modal dialog (determined by attribute role="dialog")
            if ($(target).parents('[role=dialog]').length) {                            
                // Find first or last input element in the dialog parent (depending on whether Shift was pressed). 
                // Input elements must be visible, and can be Input/Select/Button/Textarea.
                var borderElem = shiftPressed ?
                                    $(target).closest('[role=dialog]').find('input:visible,select:visible,button:visible,textarea:visible').first() 
                                 :
                                    $(target).closest('[role=dialog]').find('input:visible,select:visible,button:visible,textarea:visible').last();
                if ($(borderElem).length) {
                    if ($(target).is($(borderElem))) {
                        return false;
                    } else {
                        return true;
                    }
                }
            }
        }
        return true;
    });
    

提交回复
热议问题