简体   繁体   中英

How can I animate dialog position to the center of a page?

Here is my code:

dialog = $(this).closest('.ui-dialog')
dialog.animate({
    left: document.width - dialog.width(), // or you might want to use .outerWidth()
    top: document.height - dialog.height()
}, 1000);

I want to position jQuery dialog at the center of the page with animation. I just do not understand why it is not working. Can anyone help me?

I actually prefer position:fixed . Here is a simple demo of a dialogue that transitions to the center of the browser window.

Demo: http://jsfiddle.net/FJPjQ/show
Source: http://jsfiddle.net/FJPjQ/


Basically it takes a position:fixed div and gives it a left value of 50% and a top value of 50%. This places the top left corner of the dialogue in the center of the window. To make the dialogue itself center, you can then give it a top margin of negative half its height and a left margin of half its width.

jQuery

var dialogue = $('.ui-dialog')

dialogue.animate({
    left: "50%",
    top: "50%",
    marginLeft:  -dialogue.width()/2,
    marginTop: -dialogue.height()/2
}, 1000);

HTML

<div class="ui-dialog">hi there</div>

CSS

.ui-dialog
{
    width: 200px;
    height: 50px;
    background: red;

    /* change these to change where it slides in from */
    top: -100px;
    margin-left: -100px;
    left: 50%;

    /* and this is what makes it work */
    position: fixed;
}

This code snippet can help you to center and animate at the same time:

$("#myJQUIdialog").parent().position({
    my: "center",
    at: "center",
    of: window,
    using: function (pos, ext) {
        $(this).animate({ top: pos.top }, 600);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM