jQuery 垂直对齐动画

标签 jquery css

我有一些内容在中间垂直对齐。单击按钮时,我希望将所述内容更改为 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);
});

JS Bin

最佳答案

不幸的是,您无法设置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/

相关文章:

javascript - 将 youtube iframe 放在另一个带有图标关闭的框架上

html - 如何在一行中用两个 <div> 围绕图像?

html - div 将内容与其他 div 对齐

javascript - Jquery 移动日期框今天按钮点击关闭

javascript - 页面刷新后执行jQuery函数

javascript - 从 json 响应动态创建模态

javascript - jQuery 无法在输入中添加类

jquery - 如何通过主干事件处理程序获取触发事件的元素

css - 免费 wordpress.com 网站上的全 Angular 页面

javascript - 代码不显示 json 页面中的数据