尝试使用jquery animate函数将DIV定位在浏览器视口窗口的中心

时间:2014-11-25 07:35:18

标签: jquery

我试图使用jquery animate函数将DIV定位在浏览器视口窗口的中心。

问题是DIV不在中心,而div是位置靠近中心。

所以我关心的是我没有找到哪个div没有位于浏览器视口窗口uisng jquery animate函数的中心。

这是我的完整代码。所以请看我的代码并指导我缺少的东西。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type='text/javascript'>
    $(document).ready(function () {
        $("#Button1").click(function () {
            $("form #UPSContainer").each(function () {
                $(this).remove();
            });

            $('form').append('<div id="UPSContainer" class="hidden" style="background:red;display:none;position:absolute"></div>');
            if ($("#UPSContainer").exists() == true) {
                $("#UPSContainer").css({ height: 0, width: 0, display: 'block' });

                var xleft = ($(window).width() - $("#UPSContainer").width());
                var xtop = ($(window).height() - $("#UPSContainer").height());

                $("#UPSContainer").css({ left: xleft, top: xtop });
                $("#UPSContainer").animate({
                    left: (($(window).width() - $("#UPSContainer").width()) / 2) + 'px',
                    top: (($(window).height() - $("#UPSContainer").height()) / 2) + 'px',
                    height: 100 + 'px', width: 100 + 'px'
                }, 200,
                function () {
                    //$("#feed_dialog").removeClass("BusyStyles").find('#acloginpod').fadeIn(2000);
                });

            }
            return false;
        });


        jQuery.fn.exists = function () { return this.length > 0; }
    });

</script>
</head>
<body>
<form method="post" action="WebForm1.aspx" id="ctl00">
<input type="submit" name="Button1" value="Fly DIV" id="Button1" style="display:block" />
</form>
</body>
</html>

修改

这是jsfiddle link。我试图从右下角看出我的div。最初我的div的大小为零,当它移动到中心时,它的大小会增加。

我不知道为什么div没有位于屏幕中央。

修改

我使用你的代码并修改位以获得我的输出。这是我的完整代码和js fiddle link

HTML

<input type="submit" name="Button1" value="Fly DIV" id="Button1" class="toggleUPSContainer" />

<div class="UPS_rate_time">
<div class="information">UPS Time and Transit Details</div>
<div class="national">
<span style="color:White;font-weight:bold;">National</span>
<ul>
<li>1 Business Day</li>
<li>Delivery by 9:00 a.m</li>
<li>UPS Express Plus</li>
</ul>

<ul>
<li>1 Business Day</li>
<li>Delivery by 9:00 a.m</li>
<li>UPS Express Plus</li>
</ul>

<ul>
<li>1 Business Day</li>
<li>Delivery by 9:00 a.m</li>
<li>UPS Express Plus</li>
</ul>


</div>

<div class="international">
<span style="color:White;font-weight:bold;">International</span>

<ul>
<li>1 Business Day</li>
<li>Delivery by 9:00 a.m</li>
<li>UPS Express Plus</li>
</ul>

<ul>
<li>1 Business Day</li>
<li>Delivery by 9:00 a.m</li>
<li>UPS Express Plus</li>
</ul>

<ul>
<li>1 Business Day</li>
<li>Delivery by 9:00 a.m</li>
<li>UPS Express Plus</li>
</ul>
</div>
<div class="tntclose">Close</div>
</div>

CSS

 #UPSContainer{
        position: absolute;
        display: none;
        background:white;
        height:0;
        width:0;
        position:fixed;
        border: thin solid black;
    }  

    /* TNT Style Start*/
        .UPS_rate_time
        {
            border: thin solid black;
            width: 600px;
            height: auto!;
            min-height: 360px;
            overflow: hidden;
            display: none;
        }

        .information
        {
            background: #3ab54b;
            width: auto;
            padding: 20px;
            color:White;
            font-weight:bold;
            font-size:26px;
        }

        .national, .international
        {
            width: 49%;
            float: left;
            height: auto;
            overflow: hidden;
            padding-bottom: 10px;
            margin-left:3px;
        }

        .national
        {
        }

        .international
        {
            margin-left: 1%;
        }

        .national span, .international span
        {
            display: block;
            background: #3ab54b;
            padding: 5px;
            margin-top: 10px;
        }

        .national ul
        {
            margin: 9px 59px -8px -31px;
            height: auto;
            display: block;
            overflow: hidden;
            border-bottom: thin solid #ccc;
            width: 100%;
        }

        .national ul li
        {
            float: left;
            display: block;
            list-style: none;
            width: 30%;
            text-align: left;
            margin: 1px;
            border-right: thin solid #ccc;
            padding: 2px;
        }

        .national ul:nth-child(odd)
        {
            background: #eee;
        }

        .international ul
        {
            margin: 9px 59px -8px -31px;
            height: auto;
            display: block;
            overflow: hidden;
            border-bottom: thin solid #ccc;
            width: 100%;
        }
        .international ul li
        {
            float: left;
            display: block;
            list-style: none;
            width: 30%;
            text-align: left;
            margin: 1px;
            border-right: thin solid #ccc;
            padding: 2px;
        }

        .international ul:nth-child(odd)
        {
            background: #eee;
        }

        .tntclose
        {
            border: thin solid #3ab54b;
            float: right;
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
            margin-right: 20px;
            cursor: pointer;
            background: #3ab54b;
            color:White;
            font-weight:bold;
        } 

js code

var flag = false;
        $(document).ready(function () {
            var $els = [];
            var data = {
                "UPSContainer": {
                    "height": 360,
                    "width": 600
                },
                "isAnimating": false
            };
            $els.window = $(window);
            $els.body = $('body');
            $els.toggleUPSButtons = $('.toggleUPSContainer');
            $els.tntclose = $('.tntclose');

            function addUPSOverlay() {
                $els.body.append('<div id="UPSContainer"></div>');
                $els.UPSContainer = $('#UPSContainer');
                $els.UPSContainer.css({ opacity: 0 });
            }

            function getNewWindowCorner() {
                data.windowWidth = parseInt($els.window.width());
                data.windowHeight = parseInt($els.window.height());
                if ($els.UPSContainer.is(':hidden')) {
                    $els.UPSContainer.css({
                        top: data.windowHeight + 'px',
                        left: data.windowWidth + 'px'
                    });
                } else {
                    $els.UPSContainer.css({
                        left: ((data.windowWidth - data.UPSContainer.width) / 2) + 'px',
                        top: ((data.windowHeight - data.UPSContainer.height) / 2) + 'px'
                    });
                }
            }

            function containerOpenComplete() {
                // do what you want here when opening complete
            }

            function containerCloseComplete() {
                // do what you want here when closing complete
            }

            function toggleUPSOverlay(e) {
                //e.preventDefault();
                if (!data.isAnimating) {
                    if ($els.UPSContainer.is(':hidden')) { // currently closed so open
                        data.isAnimating = true;
                        $els.UPSContainer.show();
                        $els.UPSContainer.animate({
                            left: ((data.windowWidth - data.UPSContainer.width) / 2) + 'px',
                            top: ((data.windowHeight - data.UPSContainer.height) / 2) + 'px',
                            height: data.UPSContainer.height + 'px',
                            width: data.UPSContainer.width + 'px',
                            opacity: 1
                        },
                        { duration: 800, queue: false, easing: 'easeOutQuart',
                            step: function (now, tween) {
                                if (tween.prop === 'width') {
                                    if (now >= 250) {
                                        //console.log('Width reached 50%');
                                        if (!flag) {
                                            flag = true;
                                            //$("body").append('Width reached 50%' + now);
                                        }
                                    }
                                }
                            },

                            complete: function () {
                                $els.UPSContainer.append($('.UPS_rate_time').fadeIn(300));
                                data.isAnimating = false;
                            }
                        });
                    } else { // currently open so close
                        data.isAnimating = true;
                        $els.UPSContainer.animate({
                            left: data.windowWidth + 'px',
                            top: data.windowHeight + 'px',
                            height: 0 + 'px',
                            width: 0 + 'px',
                            opacity: 0
                        },
                        { duration: 800, queue: false, easing: 'easeOutQuart',
                            complete: function () {
                                $('.UPS_rate_time').fadeOut('slow').css({ display: 'none' });
                                $els.UPSContainer.hide();
                                data.isAnimating = false;
                            }
                        });
                    }
                }
                return false;
            }

            function attachEvents() {
                $els.window.bind('resize', getNewWindowCorner);
                $els.toggleUPSButtons.bind('click', toggleUPSOverlay);
                $els.tntclose.bind('click', toggleUPSOverlay);
            }

            function initialize() {
                addUPSOverlay();
                getNewWindowCorner();
                attachEvents();
                toggleUPSOverlay();
            }

            initialize();
        });

1 个答案:

答案 0 :(得分:0)

这可以通过简单的CSS3来解决。

您当前正将元素的左上角定位在屏幕中央。要么你可以为你的js添加更多代码。或者添加这5行CSS

#UPSContainer{
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    -o-transform: translateX(-50%) translateY(-50%);
    -ms-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}

<强> DEMO


编辑:使用负边距交叉浏览器

另一种方法是在fly div上使用负边距。请注意,此选项仅在您知道元素的结束高度和宽度将会是什么时才会起作用(看起来您无论如何都要在动画中设置它)

$(document).ready(function () {
    $("#Button1").click(function () {
        $("form #UPSContainer").each(function () {
            $(this).remove();
        });

        $('form').append('<div id="UPSContainer" class="hidden" style="background:red;display:none;position:absolute"></div>');
        if ($("#UPSContainer").exists() == true) {
            $("#UPSContainer").css({ height: 0, width: 0, display: 'block' });

            var xleft = ($(window).width() - $("#UPSContainer").width());
            var xtop = ($(window).height() - $("#UPSContainer").height());

            $("#UPSContainer").css({ left: xleft, top: xtop });
            $("#UPSContainer").animate({
                left: (($(window).width() - $("#UPSContainer").width()) / 2) + 'px',
                top: (($(window).height() - $("#UPSContainer").height()) / 2) + 'px',
                height: 100 + 'px', 
                width: 100 + 'px',
                marginLeft: '-50px',
                marginTop: '-50px'
            }, 200,
            function () {
                //$("#feed_dialog").removeClass("BusyStyles").find('#acloginpod').fadeIn(2000);
            });

        }
        return false;
    });


    jQuery.fn.exists = function () { return this.length > 0; }
});

<强> DEMO


编辑:请求打开和关闭框的方法

显着更改了您的代码。我这样做了,因为如果我只是使用你提供的代码,将会有很多重复的步骤。 jQuery DOM搜索的缓存,存储全局变量的数据属性,允许窗口大小调整的更新,元素的单个DOM插入,都是为了编写快速的jQuery代码而完成的。

您现在可以使用多个按钮来打开/关闭叠加层..只需为它们提供课程toggleUPSContainer

$(document).ready(function () {
    var $els = [];
    var data = {
        "UPSContainer": {
            "height" : 100,
            "width" : 100
        },
        "isAnimating" : false
    };
    $els.window = $(window);
    $els.form = $('#ctl00');
    $els.toggleUPSButtons = $('.toggleUPSContainer');

    function addUPSOverlay(){
        $els.form.append('<div id="UPSContainer"></div>');
        $els.UPSContainer = $('#UPSContainer');
    }

    function getNewWindowCorner(){
        data.windowWidth = parseInt($els.window.width());
        data.windowHeight = parseInt($els.window.height());
        if($els.UPSContainer.is(':hidden')){
            $els.UPSContainer.css({
                top: data.windowHeight + 'px',
                left: data.windowWidth + 'px'
            });
        }else{
            $els.UPSContainer.css({
                left: ((data.windowWidth - data.UPSContainer.width) / 2) + 'px',
                top: ((data.windowHeight - data.UPSContainer.height) / 2) + 'px'
            });
        }
    }

    function containerOpenComplete(){
        // do what you want here when opening complete
    }

    function containerCloseComplete(){
        // do what you want here when closing complete
    }

    function toggleUPSOverlay(e){
        e.preventDefault();
        if(!data.isAnimating){
            if($els.UPSContainer.is(':hidden')){ // currently closed so open
                $els.UPSContainer.show();
                $els.UPSContainer.animate({
                        left: ((data.windowWidth - data.UPSContainer.width) / 2) + 'px',
                        top: ((data.windowHeight - data.UPSContainer.height) / 2) + 'px',
                        height: data.UPSContainer.height + 'px', 
                        width: data.UPSContainer.width + 'px'
                }, 200, function(){
                    containerOpenComplete();
                });
            }else{ // currently open so close
                $els.UPSContainer.animate({
                        left: data.windowWidth + 'px',
                        top: data.windowHeight + 'px',
                        height: 0 + 'px', 
                        width: 0 + 'px'
                    }, 200,
                    function () {
                        $els.UPSContainer.hide();
                        containerCloseComplete();
                    });
            }
        }
    }

    function attachEvents(){
        $els.window.on('resize', getNewWindowCorner);
        $els.toggleUPSButtons.on('click', toggleUPSOverlay);
    }

    function initialize(){
        addUPSOverlay();
        getNewWindowCorner();
        attachEvents();
    }

    initialize();
});

<强> DEMO