直接上例子,利用原生CSS3实现了一个非常简单的点击切换显示和隐藏,主要利用了trasition过渡效果,下面介绍一下参数和使用方法:
//jsx
constructor(props){
super(props);
this.state = {
show: true
}
}
render() {
return (
<Fragment>
<div className={this.state.show ? 'show' : 'hide'}>hello</div>
<button onClick={this.handleToggole}>toggle</button>
</Fragment>
)
}
handleToggole: ()=> {
this.setState({
show: this.state.show ? false : true
})
}
//css
.show {
opacity: 1;
transition: all 1s ease-in 0; //过渡效果
}
.hide {
opacity: 0;
transition: all 1s ease-in 0;
}
transition接收4个参数,分别是:
transition: property //应用的css属性
duration //第一个参数为all,动画持续时间
timing-function //时间曲线
delay //延迟多少毫秒后执行
第1个参数的all为全部,也可以拆分到具体属性,如:
transition: background 1s ease 2s,
border-radius 3s ease 1s;
关于第3个参数时间曲线下面给大家列出了内置选项,请大家打开浏览器F12自行查看详细的曲线
linear 规定以相同速度开始至结束的过渡效果(等于 cubic-bezier(0,0,1,1))。
ease 规定慢速开始,然后变快,然后慢速结束的过渡效果(cubic-bezier(0.25,0.1,0.25,1))。
ease-in 规定以慢速开始的过渡效果(等于 cubic-bezier(0.42,0,1,1))。
ease-out 规定以慢速结束的过渡效果(等于 cubic-bezier(0,0,0.58,1))。
ease-in-out 规定以慢速开始和结束的过渡效果(等于 cubic-bezier(0.42,0,0.58,1))。
cubic-bezier(n,n,n,n) 在 cubic-bezier 函数中定义自己的值。可能的值是 0 至 1 之间的数值。
我们也可以用@keyframes自定义动画效果,类似于flash中的帧数,我们将css文件改写如下内容:
//css
.show {
animation: show-item 2s ease-in forwards;
}
.hide {
animation: hide-item 2s ease-in forwards;
}
@keyframes show-item {
0% {
opacity: 0;
color: red;
}
50% {
opacity: 0.5;
color: green;
}
100% {
opacity: 1;
color: blue;
}
}
@keyframes hide-item {
0% {
opacity: 1;
color: red;
}
50% {
opacity: 0.5;
color: green;
}
100% {
opacity: 0;
color: blue;
}
}
animation也是一个简写属性,以下是详细的属性值:
animation-name //规定需要绑定到选择器的 keyframe 名称。
animation-duration //规定完成动画所花费的时间,以秒或毫秒计。
animation-timing-function //规定动画的速度曲线。
animation-delay //规定在动画开始之前的延迟,默认是0,可以省略。
animation-iteration-count //规定动画应该播放的次数。
animation-direction //规定是否应该轮流反向播放动画。
这里还要注意,forwards其实不是属于animation的属性值,而是animation-fill-mode的一个属性,如果不加forwards,动画结束后会回到最初始的状态,加上forwards动画结束后会保存结束的状态。
网友评论