在Bootstrap模式处于活动状态时禁用Tab键聚焦

clx*_*lxe 4 twitter-bootstrap

在Bootstrap 3中,我有一个模式窗口,当您单击.btn链接时会弹出该窗口.

当它处于活动状态时,用户仍然可以按下Tab以关注背景中的链接和按钮,其中一些具有工具提示等.当这些链接被聚焦时,它们的工具提示与模态窗口重叠,这看起来很傻.

有没有办法Tab在模态窗口处于活动状态时禁用,并Tab在关闭时重新启用?

Dar*_*ryl 8

此解决方案仍允许Tab键在模式中的任何可聚焦元素上正常运行.只需在DOM加载后调用它,它就可以用于页面上的任何模态.

disableTabModalShown = function () {

$('.modal').on('shown.bs.modal', function() {

    var modal = $(this);
    var focusableChildren = modal.find('a[href], a[data-dismiss], area[href], input, select, textarea, button, iframe, object, embed, *[tabindex], *[contenteditable]');
    var numElements = focusableChildren.length;
    var currentIndex = 0;

    $(document.activeElement).blur();

    var focus = function() {
        var focusableElement = focusableChildren[currentIndex];
        if (focusableElement)
            focusableElement.focus();
    };

    var focusPrevious = function () {
        currentIndex--;
        if (currentIndex < 0)
            currentIndex = numElements - 1;

        focus();

        return false;
    };

    var focusNext = function () {
        currentIndex++;
        if (currentIndex >= numElements)
            currentIndex = 0;

        focus();

        return false;
    };

    $(document).on('keydown', function (e) {

        if (e.keyCode == 9 && e.shiftKey) {
            e.preventDefault();
            focusPrevious();
        }
        else if (e.keyCode == 9) {
            e.preventDefault();
            focusNext();
        }
    });

    $(this).focus();
});

$('.modal').on('hidden.bs.modal', function() {
    $(document).unbind('keydown');
});};
Run Code Online (Sandbox Code Playgroud)