【发布时间】:2013-10-21 00:52:23
【问题描述】:
我正在尝试使用 CSS 将 div 居中放置在窗口中间,然后使用 jQuery 的 animate 函数将其向左滑动。 CSS 和 animate 函数正在工作,但是当动画开始时,div 会跳到右侧,然后从该位置开始动画。
我创建了一个小提琴来演示这个问题。请注意,红色和黄色框应该从同一个中心位置开始,但红色框在窗口右侧开始动画。
http://jsfiddle.net/Zeaklous/XMKCc/2/
为了证明 animate 在没有 CSS 居中 div 的情况下也能正常工作,我在同一个小提琴中包含了两个使用 javascript 居中的框。粉红色框从我期望的位置开始动画(直接在紫色框上方)。
我可以做些什么来让以 CSS 为中心的 div 与 animate 一起正常工作吗?
代码如下
.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);
})
【问题讨论】:
-
我没有看到问题。什么粉红色的盒子?
-
@ShaanSingh 小提琴和问题中的代码不同,我更新了问题
-
它似乎正在使用 Javascript。为什么一定要用 CSS 来对齐?
标签: jquery css jquery-animate