想要在OK按钮上自动对焦的Bootstrap Modal

时间:2017-07-31 14:25:40

标签: model-view-controller less bootstrap-modal

我有一个模态。有一个OK按钮。我想把重点放在按钮上。我尝试过自动对焦,但是它会聚焦一秒然后消失。

_Layout.cshtml中的代码是:

<!-- modal that can notify users of errors -->
<div id="error-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="error-modal" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                    <span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Notice</h4>
            </div>

            <div class="modal-body">
                <ul>
                    <!-- ko foreach: ModalErrors -->
                    <li data-bind="text: $data"></li>
                    <!-- /ko -->
                </ul>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
            </div>
        </div>
    </div>
</div>

Less文件中的代码是:

#error-modal, #info-modal, #action-modal {
    .modal-dialog {
        z-index: 1100;
    }
    .modal-content {
        border-radius: 0 4px;
        //border-radius: 0;

        ul {
            padding-left: 20px;
        }
    }
    .modal-footer {
        button {
            border-radius: 0;
        }
        .btn-primary {
            background-color: @seal-yellow;
            border-color: @seal-grey;
            color: @seal-black;
        }
    }
}

3 个答案:

答案 0 :(得分:1)

如果使用bootstrap 3,你可以通过挂钩到显示模式的事件,在屏幕上显示模态后聚焦元素:

$('.modal').on('shown.bs.modal', function (e) {
  // do something...
});

请参阅Boostrap Modal events

答案 1 :(得分:0)

您可以使用此js代码执行此操作:

modal = $("#error-modal");
modal.find('.btn-primary').focus();

此代码需要jQuery

答案 2 :(得分:0)

我必须添加id =&#34; ok-notice-button&#34;到我的按钮类型...使用javascript,然后:

        <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
        </div>


$("#error-modal").on('shown.bs.modal', function (event) {
    $("#ok-notice-button").focus();
});