2

I have some content vertically aligned in the middle. At the click of a button, I would like said content to change to vertical-align: top but animate as it does so (slide up). It seems this doesn't work though:

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

4

2 回答 2

1

不幸的是,你不能为vertical-align. 除了极少数例外, animate 函数仅适用于数值。来自 jQuery animate() 文档

所有动画属性都应动画为单个数值

作为一种解决方法,您可以top动态设置内容的位置,然后对其进行动画处理:

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

工作演示

于 2013-08-02T14:17:30.963 回答
1

如果您使用测量,您现在可以为垂直对齐设置动画!

垂直对齐值

将您的垂直对齐设置为 % 或 px 之类的东西,并在其上包含一个过渡。

或者使用 jquery,应用一个包含 css 关键帧的类,如下所示:

.item5, .item6 {
  color: #fff;
  display: inline-block;
  text-align: center;
}

.item5 {
  width: 100px;
  height: 100px;
  background: #03A9F4;
}
.item6 {
  width: 150px;
  height: 150px;
  background: #ff5722;

}

.item6:after {
  content: '';
  width: 1px;
  height: 1px;
  background: black;
    -webkit-animation: move 2s infinite alternate;
     -moz-animation: move 2s infinite alternate;
       -o-animation: move 2s infinite alternate;
          animation: move 2s infinite alternate;
}

@-webkit-keyframes move { from { vertical-align: 0% } to { vertical-align: 100% }  }
   @-moz-keyframes move { from { vertical-align: 0% } to { vertical-align: 100% }  }
     @-o-keyframes move { from { vertical-align: 0% } to { vertical-align: 100% }  }
        @keyframes move { from { vertical-align: 0% } to { vertical-align: 100% }  }
<div class="item5">1</div>
<div class="item6">2</div>

我不确定浏览器是否支持!

于 2015-02-20T17:37:20.383 回答