【问题标题】:How to avoid navigation in outside of the popped up drawer如何避免在弹出的抽屉外部导航
【发布时间】:2021-10-05 16:02:03
【问题描述】:

您好,我目前正在开发一个 reactjs 网络应用程序,并尝试在网页中提供辅助功能。在一个页面中,一旦单击按钮,就会弹出一个抽屉,我想确保选项卡仅通过抽屉导航,而在展开时不会超出抽屉。我该怎么做?

这里我附上了页面的屏幕截图,包括扩展抽屉。

【问题讨论】:

    标签: html css reactjs accessibility


    【解决方案1】:

    我建议在 JavaScript 中编写一个键盘处理程序,以将制表符顺序限制为弹出的“抽屉”(或我称之为模式的)。

    Hidde de Vries 就此写了一篇出色的简短教程,请参阅 here

    我稍微调整了一下:

    // Function to trap tab movement to a specific container element
    trapFocusInArtworkModal = function (el) {
    
        // Gather all focusable elements in a list
        var query = "a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type='email']:not([disabled]), input[type='text']:not([disabled]), input[type='radio']:not([disabled]), input[type='checkbox']:not([disabled]), select:not([disabled]), [tabindex='0']"
        var focusableEls = el.querySelectorAll(query);
        var firstFocusableEl = focusableEls[0];
        var lastFocusableEl = focusableEls[focusableEls.length - 1];
    
        // Add the key listener to the modal container to listen for Tab,
        // Left Arrow, Right Arrow, Enter and Escape
        el.addEventListener('keydown', function(e) {
            var isTabPressed = (e.key === "Tab" || e.keyCode === KEYCODE_TAB);
            var isEscPressed = (e.key === "Escape" || e.keyCode === KEYCODE_ESCAPE);
    
            // Define behaviour for Tab or Shift+Tab
            if (isTabPressed) {
                // Shift+Tab
                if (e.shiftKey) {
                    if (document.activeElement === firstFocusableEl) {
                        // Move keyboard focus to the last focusable element in the container
                        lastFocusableEl.focus();
                        e.preventDefault();
                    }
                }
                
                // Tab
                else {
                    if (document.activeElement === lastFocusableEl) {
                        // Move keyboard focus to the first focusable element in the container
                        firstFocusableEl.focus();
                        e.preventDefault();
                    }
                }
            }
            
            // Define behaviour for Escape
            if (isEscPressed) {
                // This will close out the modal when the Escape key is pressed
                // by clicking the modal's close link/button
                el.querySelector("a").click();
            }
        });
    };
    
    // Find the modal
    var modal = document.querySelector("[role='dialog']");
    
    // Attach the trap keyboard function to the modal
    trapFocusInArtworkModal(modal);
    

    然后您可以附加代码以在页面加载后运行。

    【讨论】:

      猜你喜欢
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多