How to keep focus within modal dialog?

后端 未结 9 922
醉酒成梦
醉酒成梦 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:15

    Don't use any solution requiring you to look up "tabbable" elements. Instead, use keydown and either click events or a backdrop in an effective manor.

    (Angular1)

    See Asheesh Kumar's answer at https://stackoverflow.com/a/31292097/1754995 for something similar to what I am going for below.

    (Angular2-x, I haven't done Angular1 in a while)

    Say you have 3 components: BackdropComponent, ModalComponent (has an input), and AppComponent (has an input, the BackdropComponent, and the ModalComponent). You display BackdropComponent and ModalComponent with the correct z-index, both are currently displayed/visible.

    What you need to do is have a general window.keydown event with preventDefault() to stop all tabbing when the backdrop/modal component is displayed. I recommend you put that on a BackdropComponent. Then you need a keydown.tab event with stopPropagation() to handle tabbing for the ModalComponent. Both the window.keydown and keydown.tab could probably be in the ModalComponent but there is purpose in a BackdropComponent further than just modals.

    This should prevent clicking and tabbing to the AppComponent input and only click or tab to the ModalComponent input [and browser stuffs] when the modal is shown.

    If you don't want to use a backdrop to prevent clicking, you can use use click events similarly to the keydown events described above.

    Backdrop Component:

    @Component({
    selector: 'my-backdrop',
    host: {
        'tabindex': '-1',
        '(window:keydown)': 'preventTabbing($event)'
    },
    ...
    })
    export class BackdropComponent {
        ...
        private preventTabbing(event: KeyboardEvent) {
            if (event.keyCode === 9) { // && backdrop shown?
                event.preventDefault();
            }
        }
        ...
    }
    

    Modal Component:

    @Component({
    selector: 'my-modal',
    host: {
        'tabindex': '-1',
        '(keydown.tab)': 'onTab($event)'
    },
    ...
    })
    export class ModalComponent {
        ...
        private onTab(event: KeyboardEvent) {
            event.stopPropagation();
        }
        ...
    }
    

提交回复
热议问题