欢迎交换友链 laker's blog--进击的程序媛
github: https://github.com/younglaker
微博:江小湖laker
本文讲介绍 :hover、 :active、 :focus、 :checked、 media queries、 javascript控制六种方法触发css3 transition,以及 transitionend事件的使用。
:hover 最常见的是用hover:
:hover
.hover { width: 100px; height: 100px; background: #222; color: white; text-align: center; transition: all 2s ease;}.hover:hover { width: 200px; height: 200px;}
demo :active mousedown s时触发:
:active
.active { width: 100px; height: 100px; background: #222; color: white; text-align: center; transition: all 2s ease;}.active:active { width: 200px; height: 200px;}
demo :focus 文本框聚焦时(这个在很多网站的搜索框的动画效果里用到):
.focus input, .focus textarea { width: 200px; transition: width 1s ease;}.focus input:focus, .focus textarea:focus { width: 300px;}
demo :checked 用于checkboxes 和 radio buttons 被选中时:
input 1
input 2
input 3
input 4
input[type=checkbox]:checked { height: 20px; transition: all 1s ease;}input[type=checkbox]:checked { width: 30px;}
demo media queries 改变浏览器窗口大小时触发:
media
.media { width: 200px; height: 200px; background: #222; color: white; text-align: center; transition: width 1s ease;}@media only screen and (max-width : 960px) { .media { width: 100px; height: 100px; }}
demo javascript事件触发css3 transition 通过 javascript 或者 jquery 添加、删除class来完成动画,css格式类似 :hover。
例如:
以 click 事件为例,当点击方块时,变化长宽、背景色:
html:
css:
.box { width: 200px; height: 200px; background: black; -webkit-transition: all 2s ease; -moz-transition: all 2s ease; -o-transition: all 2s ease; transition: all 2s ease;}.box.clicked { width: 300px; height: 300px; background: blue;}
javascript:
$(.box).click(function() { $(this).toggleclass(clicked);});
demo 如果用原生javascript,可以自己写个添加和删除类的函数。
transitionend 事件 transitionend 事件会在 css transition 结束后触发。兼容chrome、firefox、safari、ie10+:
element.addeventlistener('transitionend', callback, false);
为保证低版本兼容性可以写webkittransitionend(webkit )、otransitionend(opera)、mstransitionend(ie 10+)、transitionend(mozilla)。 详见此讨论。
有没有渐变开始的事件?目前只有ie 10+ 有 transionstart 事件,w3c目前未有此标准。