2015-02-17 72 views
0

我在how to create an animated sticky header, with CSS3 and jQuery上实现了本文中的折叠粘贴标题。双向CSS转换

头当前动画与下面的行的所有CSS的变化:

transition: all 0.4s ease; 

当粘头施加下面的CSS特性改变:

font-size: 72px; /* --> 24px; */ 
    line-height: 108px; /* --> 48px; */ 
    height:  108px; /* --> 48px; */ 
    background: #335C7D; /* --> #efc47D; */ 
    text-align: center; /* --> left; */ 
    padding-left: auto; /* --> 20px; */ 

所以过渡所有应该优雅之间移动每个属性的现有价值和新价值。

但是,我注意到,当我向下滚动时,文字很好地向左移动。但是,当我向上滚动时,文本似乎从中间跳出,而不是在丢失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" />

回答

2

是被改变了所有的属性将被动画的假设是不正确。

只有动画属性将优雅地过渡,并且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的解决方案。