2012-04-28 67 views
10

我使用引导模式插件。但模态对话框不显示在中心。 为什么?我的错?Bootstrap 2的模态插件不会显示在中心

http://dl.dropbox.com/u/573972/stackoverflow/bootstrap/modal.html

<!DOCTYPE html> 
<head> 
    <meta charset="utf-8"> 
    <title>test</title> 
    <meta name="description" content=""> 
    <meta name="author" content=""> 
    <!-- Mobile Specific--> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <!-- CSS--> 
    <link rel="stylesheet" href="bootstrap.min.css"> 
    <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js'></script> 
</head> 
<body> 
    <div id="login" class="modal"> 
    <div class="modal-header"> 
     <h3>Login to Room fuga</h3> 
    </div> 
    <div class="modal-body"> 
     hogehoge 
    </div> 
    </div> 
    <script src="bootstrap.min.js"> 
    </script> 
    <script> 
$('#login').modal(); 
</script> 
</body> 
</html> 

回答

18

我发现这个workarround来解决这个问题:

$('#YourModal').modal().css(
      { 
       'margin-top': function() { 
        return -($(this).height()/2); 
       } 
      }) 

来源:https://github.com/twitter/bootstrap/issues/374

+3

此解决方案不起作用:http://jsfiddle.net/sonic1980/szFtE/ – Peter 2012-12-30 16:19:16

+0

谢谢,保存当天 – 2013-03-29 06:35:42

+0

我删除了减去之前($ this)添加积极的顶部边距,而不是负边距,并且在对话框中垂直对齐我的对话框3.直接使用解决方案似乎将我的对话框移动到可见区域之外。 – angularsen 2013-12-09 17:45:15

9

如果你的twitter引导模态对话框不是水平居中的,你可以通过css修复这个问题。

只给模式对话框一个负的左边距,它的宽度是它的一半,例如,所以:

.modalDialogBlabla { 
    margin: 0 0 0 -250px; 
    width: 500px; 
    } 
+2

很干净,很漂亮的解决答案!虽然它没有回答这个问题(垂直居中),但它的工作方式像水平的魅力。 – 2013-01-19 15:24:18

+0

耶谢谢! – the0ther 2013-02-13 18:18:38

+0

真棒。如果你不使用默认值,那么节省很多时间。谢谢ner12ss! – Hcabnettek 2014-04-28 21:30:51

8

.modal后的show事件计算新的位置:

$('body').on('show', '.modal', function(){ 
    $(this).css({'margin-top':($(window).height()-$(this).height())/2,'top':'0'}); 
});​ 

DEMO:http://jsfiddle.net/sonic1980/b2EHU/

2

基于p4810的回答同上,但处理当用户也在屏幕上。与绝对定位一起工作。

$('#YourModal').modal().css(
      { 
       'margin-top': function() { 
        return window.pageYOffset-($(this).height()/2); 
       } 
      }); 
+0

IE9无法正常工作,有没有什么IE浏览器不明白这一点? – Notflip 2014-01-29 15:27:12