bootstrap弹出的模态框水平垂直居中的实现

学习javascript从入门到放弃!bootstrap弹出的模态框水平垂直居中的实现,这是第一篇随笔,经验不足,如有不当之处,还望指出。好了废话不多说直接切入正题吧bootstrap弹出的模态框水平垂直居中的实现

 

1.bootstrap默认的model写法:

//触发模态框的button
<button data-toggle="modal" data-target="#myModal"type="button"
class="btn btn-default" >button
</button>
//弹出的模态框内容
<div id="myModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">                                                                                                                                   //关闭模态框
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true"><img src="/static/img/modal-close.png"/></span>
          </button>
                <h4 class="modal-title f24" id="mySmallModalLabel">支付</h4>
            </div>
            <div class="modal-body">
            
            </div>
        </div>
    </div>
</div>

 //通过javascript调用,只需一行 JavaScript 代码,即可通过元素的 id myModal 调用模态框:

$('#myModal').modal();

2.实现水平垂直居中

使用modal弹出事件方法。bootsrtap的模态框提供了一些事件用于监听并执行自己的代码。我们先看一下bootstrap提供的了哪些事件及基本用法;

bootstrap弹出的模态框水平垂直居中的实现

从上面的图片中可以了解到bootstrap提供的这些事件应用的条件。我们的需求是:在触发modal显示的时候,modal出现在页面的水平垂直居中位置,那么show.bs.modal恰恰符合我们的需求。so,我们可以这样写

$('#myModal').on('show.bs.modal',function(e){
    //设置模态框的水平垂直方向的位置;
});

里面的function(e){};可以拿出在单独定义一个function,这里命名为centerModals,

function centerModals() {   
  $(
'#myModal').each(function(i) {     var $clone = $(this).clone().css('display','block').appendTo('body');     var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);     top = top > 0 ? top : 0;     $clone.remove();     $(this).find('.modal-content').css("margin-top", top);   }); };

最后在show.bs.modal事件中调用centerModals函数:

$('#myModal').on('show.bs.modal', centerModals);
//禁用空白处点击关闭
$('#myModal').modal({
backdrop: 'static',
keyboard: false,//禁止键盘
show:false
});
//页面大小变化是仍然保证模态框水平垂直居中
$(window).on('resize', centerModals);

 到此大功告成!bootstrap弹出的模态框水平垂直居中的实现,希望对帮助到大家。

如有不当之处,还望赐教。


共勉:  

  人生的路上没有地图,我们一路走一路在寻找,我们每个人心中都有梦想,但没有人知道抵达目的地的正确线路,所以我们在黑夜中摸索前行。

  人生的路上没有地图,我们一路走一路被辜负,每一条寻梦的路上都充满荆棘和陷阱,每一个奋斗的人生都充满了挫折和辜负。但即使被打倒,也要站起来,掸掸身上的土,继续前行;即使被辜负,也要笑一笑,把它抛之脑后,接着上路。

  因为人生没有地图,只要你勇敢走下去,就永远不会迷路!