使用Jquery动画将相对元素居中

使用Jquery动画将相对元素居中,jquery,html,css,Jquery,Html,Css,我有一个相对位置的div#样本,没有预定义的宽度;我想在移动它之后使用以下命令将其居中: $('#sample').animate({ "left": -3000 }, 1500); $('#sample').animate({ 'left': x }, 1500); 我的问题是我不知道如何计算x。以防万一#样本将处于绝对位置,我知道这一点。但是,我需要相对位置和$(“#sample”).width()与其实际宽度不一致,以便使用它来查找中心。有什么办法帮我吗? 非常感谢如果计

我有一个相对位置的div#样本,没有预定义的宽度;我想在移动它之后使用以下命令将其居中:

$('#sample').animate({
    "left": -3000
}, 1500);
$('#sample').animate({
    'left': x
}, 1500);
我的问题是我不知道如何计算x。以防万一#样本将处于绝对位置,我知道这一点。但是,我需要相对位置和$(“#sample”).width()与其实际宽度不一致,以便使用它来查找中心。有什么办法帮我吗?

非常感谢

如果计算元素及其父元素的宽度,则可以按如下方式将其居中

var elemWidth = $('#sample').width();
var parentWidth = $('#sample').parent().width();
$('#sample').animate({ 'left': (parentWidth/2-elemWidth/2)}, 1500 );
示例

js

$(document).ready(function(){
    $('#sample').animate({ "left": -3000 }, 1500 );
    $('input[type="button"]').click(function(){
        var elemWidth = $('#sample').width();
        var parentWidth = $('#sample').parent().width();
        $('#sample').animate({ 'left': (parentWidth/2-elemWidth/2)}, 1500 );
    });
});
div{
    position:relative;
    background-color:lightgrey;
    width:200px;/*random width*/
}
html

<div id="sample">this is a test</div>
<input type="button" value="animate"/>

如果计算元素及其父元素的宽度,则可以按如下方式将其居中

var elemWidth = $('#sample').width();
var parentWidth = $('#sample').parent().width();
$('#sample').animate({ 'left': (parentWidth/2-elemWidth/2)}, 1500 );
示例

js

$(document).ready(function(){
    $('#sample').animate({ "left": -3000 }, 1500 );
    $('input[type="button"]').click(function(){
        var elemWidth = $('#sample').width();
        var parentWidth = $('#sample').parent().width();
        $('#sample').animate({ 'left': (parentWidth/2-elemWidth/2)}, 1500 );
    });
});
div{
    position:relative;
    background-color:lightgrey;
    width:200px;/*random width*/
}
html

<div id="sample">this is a test</div>
<input type="button" value="animate"/>