jquery - 使用 Jquery animate 将相对元素居中

标签 jquery html css

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

$('#sample').animate({
    "left": -3000
}, 1500);
$('#sample').animate({
    'left': x
}, 1500);

我的问题是我不知道如何计算 x。如果#sample 是绝对定位的,我就知道了。但是,我想要相对位置并且 $("#sample").width() 与其实际宽度不一致,无法使用它来寻找中心。有什么想法可以帮助我吗?
非常感谢

最佳答案

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

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

示例

http://jsfiddle.net/wQ3K7/

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 );
    });
});

html

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

CSS

div{
    position:relative;
    background-color:lightgrey;
    width:200px;/*random width*/
}

关于jquery - 使用 Jquery animate 将相对元素居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20312513/

相关文章:

javascript - 使用 javascript 设置页面加载时的默认引导日期和日期时间值

html - 父 div 出现时子 div 不出现

javascript - 更改可折叠菜单标题中的文本会导致其消失

html - float 不适用于文本和图像元素

javascript - 如何使用 jquery 将 ".01"添加到文本框值

javascript - 无法使该图像 slider 在多个实例中工作

css - nivo slider 的定位

html - 网站上表格列的重新排序

jquery - 不接受 Jquery .html() 中的变量

javascript - 从文件名javascript中删除非法字符