-1

I am trying to center a div in the middle of the window using CSS and then slide it to the left using the jQuery's animate function. The CSS and animate function are working, however when the animation starts, the div jumps to the right and then animates from that location.

I have created a fiddle to demonstrate the problem. Notice that the red and yellow boxes should start at the same centered location, but the red box starts animating further right in the window.

http://jsfiddle.net/Zeaklous/XMKCc/2/

To prove to myself that animate works correctly without a CSS centered div, I included two boxes centered using javascript in the same fiddle. The pink box animates from the position that I would expect (directly over the purple one).

Is there anything I can do to get the CSS centered div working correctly with animate?

Code below

.centeredByCSS {
    left:0;
    right:0;
    margin:0 auto;
    width:50px;
    height:50px;
    position:absolute;
}

.centeredByJS {
    width:50px;
    height:50px;
    position:absolute;
    top:75px;
}

.yellow {
    background:yellow;
}

.red {
    background:red;
}

.purple {
    background:purple;
}

.pink {
    background:pink;
}

<div id="box1" class="centeredByCSS red">TEST1
</div>

<div id="box2" class="centeredByCSS yellow">TEST2
</div>

<div id="box3" class="centeredByJS purple">TEST3
</div>

<div id="box4" class="centeredByJS pink">TEST4
</div>

$(function(){
    //manually center the purple and pink boxes
    var location=(window.innerWidth/2)-parseInt($("#box3").css("width"))/2;
    $("#box3").css("left", location);
    $("#box4").css("left", location);

    // now animate two of the boxes 100 pixels left
    $("#box1").animate({left: "-100"}, 10000);
    $("#box4").animate({left: "-100"}, 10000);
})
4

1 回答 1

1

这是因为您将其居中的 CSS 标记不正确。当您拥有position:absolute;时,margin:0 auto;不会将您的对象居中。相反,您将需要使用元素宽度一半的left:50%负数margin-left,如下所示:

.centeredByCSS {
    left:50%;
    margin-left:-25px;
    right:0;
    width:50px;
    height:50px;
    position:absolute;
}

此外,如果您想将对象从其当前位置向左移动 -100px,您应该使用-=

$("#box1").animate({left: "-=100px"}, 10000);
$("#box4").animate({left: "-=100px"}, 10000);

更新小提琴

于 2013-10-21T01:53:40.767 回答