Bootstrap: 弹出窗口上下居中, 弹出modal上下居中, How to align Bootstrap modal vertically center

 

使用CSS margin-top属性

默认情况下,Bootstrap模式窗口与页面顶部对齐,但有一些余量。但是您可以使用简单的JavaScript技巧在页面中间垂直对齐它,如下例所示。此解决方案将动态调整模态的对齐方式,即使用户调整浏览器窗口大小,也始终将其保留在页面的中心。

<!DOCTYPE html>
<html lang="en">
<head>
<title>Vertical Center Alignment of Bootstrap Modal Dialog</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    function alignModal(){
        var modalDialog = $(this).find(".modal-dialog");
        /* Applying the top margin on modal dialog to align it vertically center */
        modalDialog.css("margin-top", Math.max(0, ($(window).height() - modalDialog.height()) / 2));
    }
    // Align modal when it is displayed
    $(".modal").on("shown.bs.modal", alignModal);
    
    // Align modal when user resize the window
    $(window).on("resize", function(){
        $(".modal:visible").each(alignModal);
    });   
});
</script>
</head>
<body>
    <!-- Button HTML (to Trigger Modal) -->
    <p><a href="#myModal" class="btn btn-lg btn-primary" data-toggle="modal">Launch Demo Modal</a></p>
    
    <!-- Modal HTML -->
    <div id="myModal" class="modal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">Confirmation</h4>
                </div>
                <div class="modal-body">
                    <p>Do you want to save changes you made to document before closing?</p>
                    <p class="text-warning"><small>If you don't save, your changes will be lost.</small></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>    
</body>
</html>

 

alignModal()上面示例中的函数通过简单地.modal-dialog在使用shown.bs.modal事件向用户显示模态时应用元素的上边距来对齐Bootstrap模式。margin-top通过从浏览器窗口的高度减去模态对话框的高度的1/2的值。

在应用上边距之前,我们已将获得的值与0一起传递给JavaScript Math.max()函数,该函数返回给定数字中的最大数字。这是必要的,因为如果用户以浏览器窗口的高度变得低于模态高度的方式调整浏览器窗口的大小,则在这种情况Math.max()函数返回0中边际计算的结果变为负,并且防止应用负边距。alignModal()每次调整浏览器窗口大小时我们也会调用该函数,以便它始终位于页面的中心。

 

 

 

本文: Bootstrap: 弹出窗口上下居中, 弹出modal上下居中, How to align Bootstrap modal vertically center

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.