我有一些内容在中间垂直对齐。单击按钮时,我希望将所述内容更改为 vertical-align: top
但同时进行动画处理(向上滑动)。但这似乎不起作用:
HTML
<div id="container">
<div id="content">Hello World</div>
</div>
<input type="button" id="myButton" value="No Animation" />
<input type="button" id="myButton2" value="Animation" />
CSS
#container { width: 500px; height: 400px; background: #eee; }
#container:before { content: ''; display: inline-block; width: 1px; height: 100%; vertical-align: middle; background: red; }
#content { display: inline-block; vertical-align: middle; background: lime; }
JS
$('#myButton').click(function(){
$('#content').css('vertical-align', 'top');
});
$('#myButton2').click(function(){
$('#content').animate({ 'vertical-align': 'top' }, 500);
});
最佳答案
不幸的是,您无法设置vertical-align
动画。除了极少数异常(exception),animate 函数仅适用于数值。来自 jQuery animate() docs :
All animated properties should be animated to a single numeric value
作为解决方法,您可以动态设置内容的顶部
位置,然后为其设置动画:
var content = $('#content'),
contentHeight = content.height();
containerHeight = $('#container').height()
;
content.css("top", containerHeight/2 - contentHeight/2)
$('#myButton').click(function () {
content.css('top', 0);
});
$('#myButton2').click(function () {
content.animate({
'top': 0
}, 500);
});
<强> Working Demo
关于jQuery 垂直对齐动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18019072/