我有一个 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 );
示例
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/