如何中止CSS3的動畫?

前言

咱們在移動端通常使用zepto框架,與其說zepto是jquery的輕量級替代版,不如說是html5替代版
咱們在js中會用到animate方法執行動畫,這個傢伙但是真資格的動畫,徹底是css一點點變化的!
而zepto則否則,使用的是HTML5/CSS3的方案,而CSS相關是不保存元素狀態值的,也沒辦法保存,因此中止動畫就成了一大問題
咱們今天就一塊兒來討論下相關中止動畫的方案,反正沒有什麼好的......javascript

CSS3動畫原理

在現有瀏覽器中,通常有兩種模式(我只知道兩種):
一種是js動畫,他是動態改寫元素的style實現動畫,因此任意時間想中止動畫都是沒問題的,由於咱們能夠得到各個階段的狀態值
另外一種就是CSS3動畫了,至於CSS3動畫的原理,我不知道可是能夠說一點的就是——見代碼css

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title></title>
 5  <script id="Script1" type="text/javascript" class="library" src="/js/sandbox/other/zepto.min.js"></script>
 6 </head>
 7 <body>
 8     <div id="Div1" style="background-color: Orange; width: 100px; height: 100px; position: absolute;
 9         left: 0; border: 1px solid black; ">
10     </div>
11 </body>
12 <script src="../zepto.js" type="text/javascript"></script>
13 <script type="text/javascript">
14     var d = $('#d');
15     d.animate({
16         left: '100px'
17     }, 10000);
18 
19     setTimeout(function () {
20         d.html('left: ' + d.css('left'));
21     }, 1);
22 
23 </script>
24 </html>

http://sandbox.runjs.cn/show/xziwuir2html

zepto的animate事實上立刻就改變了style的值,因此咱們在裏面看到了left爲100px,雖然他正在運動
而他動畫的實現事實上使用的是CSS3的transition動畫屬性,咱們這裏來看看zepto的源碼:html5

 1 var prefix = '', eventPrefix, endEventName, endAnimationName,
 2 vendors = { Webkit: 'webkit', Moz: '', O: 'o', ms: 'MS' },
 3 document = window.document, testEl = document.createElement('div'),
 4 supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,
 5 transform,
 6 transitionProperty, transitionDuration, transitionTiming,
 7 animationName, animationDuration, animationTiming,
 8 cssReset = {}
 9 
10 function dasherize(str) { return downcase(str.replace(/([a-z])([A-Z])/, '$1-$2')) }
11 function downcase(str) { return str.toLowerCase() }
12 function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : downcase(name) }
13 
14 $.each(vendors, function (vendor, event) {
15     if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
16         prefix = '-' + downcase(vendor) + '-'
17         eventPrefix = event
18         return false
19     }
20 })
21 
22 transform = prefix + 'transform'
23 cssReset[transitionProperty = prefix + 'transition-property'] =
24 cssReset[transitionDuration = prefix + 'transition-duration'] =
25 cssReset[transitionTiming = prefix + 'transition-timing-function'] =
26 cssReset[animationName = prefix + 'animation-name'] =
27 cssReset[animationDuration = prefix + 'animation-duration'] =
28 cssReset[animationTiming = prefix + 'animation-timing-function'] = ''
29 
30 $.fx = {
31     off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
32     speeds: { _default: 400, fast: 200, slow: 600 },
33     cssPrefix: prefix,
34     transitionEnd: normalizeEvent('TransitionEnd'),
35     animationEnd: normalizeEvent('AnimationEnd')
36 }
37 
38 $.fn.animate = function (properties, duration, ease, callback) {
39     if ($.isPlainObject(duration))
40         ease = duration.easing, callback = duration.complete, duration = duration.duration
41     if (duration) duration = (typeof duration == 'number' ? duration :
42                 ($.fx.speeds[duration] || $.fx.speeds._default)) / 1000
43     return this.anim(properties, duration, ease, callback)
44 }
45 
46 $.fn.anim = function (properties, duration, ease, callback) {
47     var key, cssValues = {}, cssProperties, transforms = '',
48     that = this, wrappedCallback, endEvent = $.fx.transitionEnd
49 
50     if (duration === undefined) duration = 0.4
51     if ($.fx.off) duration = 0
52 
53     if (typeof properties == 'string') {
54         // keyframe animation
55         cssValues[animationName] = properties
56         cssValues[animationDuration] = duration + 's'
57         cssValues[animationTiming] = (ease || 'linear')
58         endEvent = $.fx.animationEnd
59     } else {
60         cssProperties = []
61         // CSS transitions
62         for (key in properties)
63             if (supportedTransforms.test(key)) transforms += key + '(' + properties[key] + ') '
64             else cssValues[key] = properties[key], cssProperties.push(dasherize(key))
65 
66         if (transforms) cssValues[transform] = transforms, cssProperties.push(transform)
67         if (duration > 0 && typeof properties === 'object') {
68             cssValues[transitionProperty] = cssProperties.join(', ')
69             cssValues[transitionDuration] = duration + 's'
70             cssValues[transitionTiming] = (ease || 'linear')
71         }
72     }
73 
74     wrappedCallback = function (event) {
75         if (typeof event !== 'undefined') {
76             if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below"
77             $(event.target).unbind(endEvent, wrappedCallback)
78         }
79         $(this).css(cssReset)
80         callback && callback.call(this)
81     }
82     if (duration > 0) this.bind(endEvent, wrappedCallback)
83 
84     // trigger page reflow so new elements can animate
85     this.size() && this.get(0).clientLeft
86 
87     this.css(cssValues)
88 
89     if (duration <= 0) setTimeout(function () {
90         that.each(function () { wrappedCallback.call(this) })
91     }, 0)
92 
93     return this
94 }
View Code

最後其實是執行anim實現咱們的動畫,你們注意看這裏
$(this).css(cssReset)
this.css(cssValues)
他事實上搞了個先設置動畫屬性,再給style屬性給元素,因此會產生動畫
到此,zepto實現動畫原理咱們大概知道了,如今問題就是如何中止他了,因此咱們繼續往下看java

如何中止動畫

咱們先看看這個東西:jquery

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title></title>
 5     <script id="Script2" type="text/javascript" class="library" src="/js/sandbox/other/zepto.min.js"></script>
 6 </head>
 7 <body>
 8     <div id="Div2" style="background-color: Orange; width: 100px; height: 100px; position: absolute;
 9         left: 0; border: 1px solid black;">
10     </div>
11 </body>
12 <script src="../zepto.js" type="text/javascript"></script>
13 <script type="text/javascript">
14     var d = $('#d');
15     d.animate({
16         left: '100px'
17     }, 10000);
18 
19     setInterval(function () {
20         d.html('left: ' + d.css('left') + ' _ offsetLeft: ' + d[0].offsetLeft);
21     }, 1);
22 
23 </script>
24 </html>

http://sandbox.runjs.cn/show/gdqezvdo

其中雖然left一開始就變了,咱們驚奇的發現,offset這個傢伙竟然保存了咱們的狀態!!!
我和個人小夥伴都驚呆了,由於我以前一直覺得什麼狀態都不能得到,因而咱們爲他加上mousedown事件,各位運動時候點擊試試
咱們這裏這樣幹了下:web

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title></title>
 5     <script id="Script3" type="text/javascript" class="library" src="/js/sandbox/other/zepto.min.js"></script>
 6 </head>
 7 <body>
 8     <div id="Div3" style="background-color: Orange; width: 100px; height: 100px; position: absolute;
 9         left: 0; border: 1px solid black;">
10     </div>
11 </body>
12 <script src="../zepto.js" type="text/javascript"></script>
13 <script type="text/javascript">
14     var d = $('#d');
15     d.animate({
16         left: '100px'
17     }, 10000);
18 
19     setInterval(function () {
20         d.html('left: ' + d.css('left') + ' _ offsetLeft: ' + d[0].offsetLeft);
21     }, 1);
22 
23     d.mousedown(function (e) {
24         console.log(d);
25         d.css('transition', 'left 0s linear');
26         d.css('left', d[0].offsetLeft + 'px');
27     });
28 
29 </script>
30 </html>

因而咱們發現,動畫中止了,親!他真的中止了!!!
PS:由於項目過程當中,我這裏要模仿相似iscroll的滾動效果,因此使用的最多的就是top或者translate3d(0, 0, 0)這種東西瀏覽器

結語

原本這裏還想深刻一點研究下的,可是如今時間有點來不及,事情有點多,暫時到這裏了吧,具體的demo爭取週末搞出來app

相關文章
相關標籤/搜索