水平和垂直中心模态Div IE问题

时间:2010-04-13 19:55:48

标签: jquery html css overlay

我正试图在div中水平和垂直居中一个模态窗口。我希望它与浏览器兼容。您可以从下面的图片中看到,当我调整IE8的大小时,然后单击“显示模态”按钮,它显示的不是完全水平居中。这似乎不是Chrome的问题。有什么想法吗?你们会怎么做到这一点?

<html>
<head>
<title>test</title>
<style type="text/css">
    *
    {
        margin: 0px;
        padding: 0px;
    }
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">

    $(function() {

        $('#modal').click(function() {

            // overlay
            $('<div id="overlay" />').css({
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                backgroundColor: 'black',
                opacity: 0
            }).appendTo('body');

            $('<div id="datamodal" />').css({
                backgroundColor: '#FFFFFF',
                border: '10px solid #999',
                height: '200px',
                width: '600px',
                position: 'absolute',
                top: '50%',
                left: '50%',
                marginTop: '-120px', 
                marginLeft: '-320px',
                color: '#111111',
                fontWeight: 'bold',
                padding: '10px',
                display: 'none'
            }).append('<input type="text" />').appendTo('#overlay');

            $('#overlay').fadeTo(300, 0.7);
            $('#datamodal').fadeIn(300);
        });

    });

</script>

</head>
<body>
    <input id="modal" type="button" value="show modal" />
</body>
</html>

alt text http://ajondeck.net/temp/resize.png

2 个答案:

答案 0 :(得分:5)

您需要根据窗口和对话框大小计算位置,并通过JavaScript设置样式。

示例来自:Using jQuery to center a DIV on the screen

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

答案 1 :(得分:1)

长时间乱搞CSS并摸不着头脑后,我注意到该文档没有DOCTYPE。我添加了一个严格的DOCTYPE,突然IE8开始表现,其余的代码都未触及。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
相关问题