摘要: 我们已经知道css3 transitions 可以让动画变得更简单和优雅, 而css3 keyframe animations 甚至可以完成复杂的细粒度的运动。 现大多主流浏览器支持transitions 和animation,这使得我们在项目中使用它们变得现实。 . ...
我们已经知道css3 transitions 可以让动画变得更简单和优雅, 而css3 keyframe animations 甚至可以完成复杂的细粒度的运动。 现大多主流浏览器支持transitions 和animation,这使得我们在项目中使用它们变得现实。 在本文中,我将讨论如何使用回调,让你更好的使用你的css3动画。 动画逻辑从js中分离先创建animation动画,让一个box变大,代码如下: css .box { width: 100px; height: 100px; background: hotpink; } @-webkit-keyframes growBox { to { width: 300px; height: 300px; } } .change-size { -webkit-animation: growBox 3s linear 1s 3 normal;} html <input type="button" id="button" value="点击我查看下面box的变化"/> <div id="box" class="box"></div> javascript var button = document.getElementById('button'), box = document.getElementById('box'), t1,t2; button.addEventListener('click', function (e) { box.classList.add('change-size'); }); 在这里,我们使用js来给动画元素添加指定的类,动画本身定义在css,它避免了脚本里到处是硬编码的css,实现分离逻辑。 Animation 监控Animatioin 可以监听三个事件,分别是:animationstart、animationend、animationiteration。
js事件绑定如下: var button = document.getElementById('button'), box = document.getElementById('box'), t1,t2; button.addEventListener('click', function (e) { box.classList.add('change-size'); console.log('动画正在执行'); t1 = +new Date(); }); box.addEventListener("webkitAnimationStart", function (e) { console.log('动画开始了,当前经历的时间:' + e.elapsedTime + 's , 经历时间不包括延迟时间:' + (e.timeStamp - t1)/1000 + 's'); }); box.addEventListener("webkitAnimationIteration", function (e) { console.log('动画重复了一次,当前经历的时间:' + e.elapsedTime + 's') }); box.addEventListener("webkitAnimationEnd", function (e) { console.log('动画结束了当前经历的时间:' + e.elapsedTime + 's'); box.classList.remove('change-size'); }); 查看效果及日志如下: 点击我查看Demo地址
<img alt="animation日志" src="http://h5dev.uc.cn/data/attachment/portal/201302/28/112242cssu99hc7ou2o8gu.png" <="" div="" style="word-wrap: break-word; max-width: 620px;">
Transition 监控Transition 可以监听事件是:transitionend。
代码及事件绑定如下: css .box { width: 100px; height: 100px; background:hotpink; -webkit-transition:width 2s linear, height 3s linear;} .change-size { width: 300px; height:300px; } html <input type="button" id="button" value="点击我查看下面box的变化"/> <div id="box" class="box"></div> javascript var button = document.getElementById('button'), box = document.getElementById('box'); button.addEventListener('click', function (e) { box.classList.add('change-size'); console.log('过渡正在执行'); }); box.addEventListener("webkitTransitionEnd", function (e) { console.log('过渡结束了,当前经历的时间:' + e.elapsedTime + 's'); }); 查看效果及日志如下: 点击我查看Demo地址
<img alt="transtion日志" src="http://h5dev.uc.cn/data/attachment/portal/201302/28/112242hdg5736465g6ddg1.png" <="" div="" style="word-wrap: break-word; max-width: 620px;">
支持情况测试u3内核8.5以上都支持监控动画。 总结动画事件的监控已有做了总结性的介绍,具体信息查看参考文献。 参考文献: |