我正在实现这篇关于 how to create an animated sticky header, with CSS3 and jQuery 的文章中的折叠粘性 header .
标题当前正在使用以下行对所有 CSS 更改进行动画处理:
transition: all 0.4s ease;
应用粘性 header 时,以下 css 属性会发生变化:
font-size: 72px; /* --> 24px; */
line-height: 108px; /* --> 48px; */
height: 108px; /* --> 48px; */
background: #335C7D; /* --> #efc47D; */
text-align: center; /* --> left; */
padding-left: auto; /* --> 20px; */
所以 transition all 应该在每个属性的现有值和新值之间优雅地移动。
但是,我注意到当我向下滚动时,文本会很好地以动画方式变小并向左移动。但是,当我向上滚动时,当失去 text-align:left
属性时,文本似乎会跳出中间而不是向右移动。
$(window).scroll(function () {
var belowTop = $(this).scrollTop() > 30;
$('header').toggleClass('sticky', belowTop);
});
/*reset */
* {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
header {
position: fixed;
width: 100%;
font-family: 'PT Sans', sans-serif;
transition: all 0.4s ease;
color: #fff;
font-size: 72px;
line-height: 108px;
height: 108px;
background: #335C7D;
text-align: center;
}
header.sticky {
font-size: 24px;
line-height: 48px;
height: 48px;
background: #efc47D;
text-align: left;
padding-left: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header><h1>Sticky Header</h1></header>
<img src="http://i.stack.imgur.com/8pezV.jpg" alt="Big Image" />
最佳答案
所有被更改的属性都将被动画化的假设是不正确的。
只有 animatable 属性会被优雅地转换,而 text-align
是不可动画的。
这是一个 complete list of animatable properties from MDN .
这是一个增加动画时间的简化示例。很容易看出,左对齐文本的动画从一开始就没有发生。
$(window).scroll(function () {
var belowTop = $(this).scrollTop() > 30;
$('header').toggleClass('sticky', belowTop);
});
header {
position: fixed;
width: 100%;
transition: all 2s ease;
font-size: 32px;
text-align: center;
}
header.sticky {
font-size: 16px;
text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header><h1>Header</h1></header>
<img src="http://i.stack.imgur.com/8pezV.jpg" alt="Big Image" />
作为动画文本对齐的解决方法,这里有几个堆栈溢出线程以及涉及其他动画属性或 jQuery 的解决方案。
关于jquery - 双向 CSS 过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28572522/