我有一个div,它是各种东西的容器。有时它包含一些简单的表和其他布局内容。但有时它包含按钮和表单。

此容器div可以模态显示另一个div。我通过简单地将其位置设置为绝对值来实现:绝对值,并且其上/下/左/右0。
看起来不错,但是当我按下选项卡按钮时,焦点可以移到后面div上的元素上。我该如何预防?

我知道我可以通过设置tabIndex = -1来禁用对一个元素的关注,因此我可以进行迭代,但是当模式消失时,我将需要恢复所有这些元素。这意味着额外的工作。我想知道是否有使用jQuery或jqueryui或vanilla js的通用方法?

编辑:
jsbin中的工作示例:
https://jsbin.com/veciju/1/edit?html,css,js,output

最佳答案

我不确定没有小提琴的确切问题是什么,并且没有检查代码。但是这是我的解决方案(纯JavaScript)希望对您有所帮助

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <div id="container">
        <p id="filler">
            Hello World.
        </p>
        <form id="myForm">
            <input type="text" />
            <input type="submit" value="submit"/>
        </form><br>
        <button id="openModal" onclick="openModal();"> Open Modal</button>

        <div id="modal" class="hidden">
            <p id="modelP"> This is a modal DIV. You cannot escape me</p>
            <button id="closeModal" onclick="closeModal();">Close Me</button>
        </div>
    </div>

</body>
<style>
    #container{
        margin: 50px auto;
        padding: 100px;
        color: white;
        width: 50%;
        height:400px;
        background-color: black;
        text-align: center;
    }

    .hidden{
        display: none;
    }

    #modal{
        background-color: green;
        border: 5px solid red;
        z-index: 100;
        width:80%;
        height: 80%;
        left: auto;

    }

</style>
<script>
    function openModal(){
        var modalElement = document.getElementById('modal');
        var others = document.querySelectorAll('* :not(#closeModal)   ');
        modalElement.removeAttribute('class');

        for (i=0; i<others.length;i++){
            console.log(others[i]);
            others[i].setAttribute('disabled','disabled');
        }



    }

    function closeModal(){
        var modalElement = document.getElementById('modal');
        var others = document.querySelectorAll('* :not(#closeModal)   ');
        modalElement.className='hidden';

        for (i=0; i<others.length;i++){
            console.log(others[i]);
            others[i].removeAttribute('disabled');
        }
    }
</script>

09-30 16:36
查看更多