如何停止CSS3的動畫?


前言

我們在移動端一般使用zepto框架,與其說zepto是jquery的輕量級替代版,不如說是html5替代版
我們在js中會用到animate方法執行動畫,這個家伙可是真資格的動畫,完全是css一點點變化的!
而zepto則不然,使用的是HTML5/CSS3的方案,而CSS相關是不保存元素狀態值的,也沒辦法保存,所以停止動畫就成了一大問題
我們今天就一起來討論下相關停止動畫的方案,反正沒有什么好的......

CSS3動畫原理

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

 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/xziwuir2

zepto的animate事實上馬上就改變了style的值,所以我們在里面看到了left為100px,雖然他正在運動
而他動畫的實現事實上使用的是CSS3的transition動畫屬性,我們這里來看看zepto的源碼:

 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實現動畫原理我們大概知道了,現在問題就是如何停止他了,所以我們繼續往下看

如何停止動畫

我們先看看這個東西:

 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事件,各位運動時候點擊試試
我們這里這樣干了下:

 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爭取周末搞出來


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM