首页 > 解决方案 > 关注基于反应的应用程序中的第一个可聚焦元素

问题描述

场景是 - 我在 page1 上有一个超链接。单击链接,将打开第 2 页。当屏幕阅读器为桌面打开时,我希望焦点落在第一个可聚焦元素上。当为移动设备打开语音时,同样的功能。

标签: javascriptreactjsfocusaccessibility

解决方案


这是实现这一点所需的 JavaScript 的基本框架,您需要将其添加到函数中并在页面加载时调用它,对 react 进行调整(不是为您编写,只是为您提供所需的指导) .

var focusableItems = ['a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', '[tabindex="0"]']; //a list of items that should be focusable.
var findString = focusableItems.join(", ");
var canFocus = Array.prototype.slice.call($('body').find(findString));

canFocus[0].focus(); 

解释

focusableItems是页面上可以接收焦点的每种选择器的列表。

findString是一个逗号分隔的选择器字符串。

canFocus是页面上可以接收使用该find方法找到的焦点的项目数组。

请注意,我使用的是自定义库,但jQuery我很确定find它的工作原理相同,但您需要检查一下。

canFocus[0].focus();聚焦页面上的第一个可聚焦项目。

这种方法可以大大简化,但我认为向您展示这些步骤会提高您的理解。

缩短版(未经测试)

Array.prototype.slice.call($('body').find('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex="0"]'))[0].focus();

对于那些没有 jQuery 的人

我使用 ki.js 的自定义实现如下,在上面的代码之前包含这个

if (typeof $ == "undefined") {
    !function (b, c, d, e, f) {

        f = b['add' + e]

        function i(a, d, i) {
            for (d = (a && a.nodeType ? [a] : '' + a === a ? b.querySelectorAll(a) : c), i = d.length; i--; c.unshift.call(this, d[i]))
                ;
        }

        $ = function (a) {
            return /^f/.test(typeof a) ? /in/.test(b.readyState) ? setTimeout(function () {
                $(a);
            }, 9) : a() : new i(a);
        };

        $[d] = i[d] = {
            on: function (a, b) {
                return this.each(function (c) {
                    f ? c['add' + e](a, b, false) : c.attachEvent('on' + a, b)
                })
            },
            off: function (a, b) {
                return this.each(function (c) {
                    f ? c['remove' + e](a, b) : c.detachEvent('on' + a, b)
                })
            },
            each: function (a, b) {
                for (var c = this, d = 0, e = c.length; d < e; ++d) {
                    a.call(b || c[d], c[d], d, c)
                }
                return c
            },
            splice: c.splice
        }
    }(document, [], 'prototype', 'EventListener');
    var props = ['add', 'remove', 'toggle', 'has'],
            maps = ['add', 'remove', 'toggle', 'contains'];
    props.forEach(function (prop, index) {
        $.prototype[prop + 'Class'] = function (a) {
            return this.each(function (b) {
                if (a) {
                    b.classList[maps[index]](a);
                }
            });
        };
    });
    $.prototype.hasClass = function (a) {
        return this[0].classList.contains(a);
    };
}
$.prototype.find = function (selector) {
    return $(selector, this);
};

推荐阅读