在Bootstrap模式激活时禁用Tab键聚焦

时间:2014-08-05 15:08:28

标签: twitter-bootstrap

在Bootstrap 3中,当您点击.btn链接时,我会弹出一个模态窗口。

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

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

2 个答案:

答案 0 :(得分: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');
});};

答案 1 :(得分:0)

您可以使用以下内容禁用Tab键。

$(document).keydown(function(e) {
    if (e.keyCode == 9) {
        e.preventDefault();
    }
});

您需要进行某种检查,以便在调用e.preventDefault()之前查看模态窗口是否打开您可以通过在模态打开/关闭上设置标记或仅检查dom元素是否可见来执行此操作

相关问题