CSS - transition简介

这篇博客意在用简短的几句话告诉你 CSS3特性 transition 的用法。

transition 有4个性质:

名称 描述
transition-property 要进行改变的元素样式
transition-duration 完成transition的总时间
transition-timing-function 变化的速度
transition-delay 延迟多久触发transition

这4个性质可以被分别设置,也可以写在一行当中,看如下实例:

<button class="btn">TRANSITION</button>
.btn {
  width: 400px;
  height: 60px;
  background-color: #3498db;
  outline: none;
  border: none;
  color: #fff;
  transition: background-color 1s ease .5s;
  /* Separated usage of transition, which has the same effects of the one-line format.
    transition-property: background-color;
    transition-duration: 1s;
    transition-timing-function: ease;
    transition-delay: .5s;
  */
}

.btn:hover {
  background-color: #e74c3c;
}

注释里的4行和上面的一行实现的效果是一样的

若想同时实现多个transition,可以像下方一样写,也可以用关键词all。

.btn {
  width: 400px;
  height: 60px;
  background-color: #3498db;
  outline: none;
  border: none;
  color: #fff;
  transition: width 1s, background-color 1s ease .5s;
  /* Separated usage of transition, which has the same effects of the one-line format.
    transition-property: width, background-color;
    transition-duration: 1s;
    transition-timing-function: ease;
    transition-delay: .5s;
  */
  /* You can even change all declared css using "all"
    transition: all 1s ease .5s;
  */
}

.btn:hover {
  background-color: #e74c3c;
}

共有两种常见的transition触发方式:

  1. 在上方例子中,我使用了hover来触发transition,这是最常见的使用方式之一。
  2. 还有一种使用方式是,事先设置好transition,通过javascript来监听DOM元素,事件发生后通过js来改变设置了transition的元素的css。
  • 这种方法更高级,可实现的效果更多。

除此之外,transition还可以与transform结合,来实现元素的移动。
照旧,附上我写的一个demo,动手试一试更能明白用法 - CSS transition属性尝试 on JSfiddle

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,342评论 1 92
  • 选择qi:是表达式 标签选择器 类选择器 属性选择器 继承属性: color,font,text-align,li...
    love2013阅读 2,486评论 0 11
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 16,732评论 4 61
  • 今日是丙申年农历正月初三,从朋友得到消息,你要结婚了。而我竟一无所知,是该责怪自己,还是这些年来你我之间从挚友...
    墨醒醒阅读 293评论 0 0
  • 男人成功,女人拜金和贪婪,有需求的市场才会催生出婚外情的滋生蔓延。 人到中年时,男人面对索然无味的婚姻生活,如果有...
    我爱微播阅读 1,183评论 0 0

友情链接更多精彩内容