到底css transition是什么,我们来看w3c的解释:
CSS Transitions allow property changes in CSS values to occur smoothly over a specified duration. This smoothing animates the changing of a CSS value when triggered by a mouse click, focus or active state, or any changes to the element (including even a change on the element’s class attribute).
翻译为中文就是:css transition允许css属性值的变化在一个时间段内平滑完成,变化的快慢可以有对应的函数来指定。这个平滑展现css值的变化过程可以由很多事件来触发,比如鼠标点击,focus,hover等。
a.foo { padding: 5px 10px; background: #9c3; -webkit-transition-property: background; -webkit-transition-duration: 0.3s; -webkit-transition-timing-function: ease; }a.foo:hover { background: #690; }
从上面的代码中,我们可以看到和transition相关的几个属性:
transition-property: 指定对哪个属性值的变更来执行对应transition动画过程;
transition-duration: 这个transition动画从开始到完成的时间段落
transition-timing-function:指定transition经由时间轴变更的节奏快慢(ease, linear, ease-in, ease-out,ease-in-out, cubic-bezier)
所有可以被transtion的css属性列表:
background-color | as |
background-position | as of of |
border-bottom-color | as |
border-bottom-width | as |
border-left-color | as |
border-left-width | as |
border-right-color | as |
border-right-width | as |
border-spacing | as of |
border-top-color | as |
border-top-width | as |
bottom | as |
clip | as |
color | as |
font-size | as |
font-weight | as |
height | as |
left | as |
letter-spacing | as |
line-height | as either or |
margin-bottom | as |
margin-left | as |
margin-right | as |
margin-top | as |
max-height | as |
max-width | as |
min-height | as |
min-width | as |
opacity | as |
outline-color | as |
outline-width | as |
padding-bottom | as |
padding-left | as |
padding-right | as |
padding-top | as |
right | as |
text-indent | as |
text-shadow | as |
top | as |
vertical-align | as |
visibility | as |
width | as |
word-spacing | as |
z-index | as |
通过程序动态添加class来触发transition
在上面的例子中,我们都是通过在元素class中设置transition属性,在sudo class中设置变更的属性值来实现的。有的时候,我们不光需要sudo class能够实现transition的触发,有什么办法吗?
这时我们可以通过javascript来动态地增加或者删除class来实现transition的触发:
/* CSS */.element { opacity: 0.0; transform: scale(0.95) translate3d(0,100%,0); transition: transform 400ms ease, opacity 400ms ease;}.element.active { opacity: 1.0; transform: scale(1.0) translate3d(0,0,0);}.element.inactive { opacity: 0.0; transform: scale(1) translate3d(0,0,0);}// JS with jQueryvar active = function(){ $('.element').removeClass('inactive').addClass('active');};var inactive = function(){ $('.element').removeClass('active').addClass('inactive');};
看上面的代码,我们将获得两种不同的transitions, 元素当activated的时候slide up,而当deactivated时fade out.所有javascript干的活儿就是切换了两个class: active和inactive
hardware acceleration
transition一些属性,比如left, margin会使得浏览器在每一个frame时都重新计算styles,这是非常昂贵的计算,会导致不必要的re-paints,特别是如果在屏幕上有非常多的元素时更是如此。一个可行的方案是使用GPU。
transform: translate3d(0,0,0);