動畫的實現原型javascript
<div id="div1" style="width:100px;height:50px;background:red;cursor:pointer;color:#fff;text-align:center;line-height:50px;">點擊</div> <script type="text/javascript"> //dom var oDiv = document.getElementById('div1'); //調用 oDiv.onclick = function() { $('#div1').run({ 'width': '500' }).run({ 'width': '300' }).run({ 'width': '1000' }); }; </script>
JScss
(function($) { window.$ = $; })(function() { var rquickExpr = /^(?:#([\w-]*))$/; function aQuery(selector) { return new aQuery.fn.init(selector); } /** * 動畫 * @return {[type]} [description] */ var animation = function(){ var self = {}; var Queue = []; //動畫隊列 var fireing = false //動畫鎖 var first = true;//經過add接口觸發 var getStyle = function(obj, attr) { return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr]; } var makeAnim = function(element, options, func) { var width = options.width //包裝了具體的執行算法 //css3 //setTimeout element.style.webkitTransitionDuration = '2000ms'; element.style.webkitTransform = 'translate3d(' + width + 'px,0,0)'; //監聽動畫完結 element.addEventListener('webkitTransitionEnd', function() { func() }); } var _fire = function() { //加入動畫正在觸發 if (!fireing) { var onceRun = Queue.shift(); if (onceRun) { fireing = true; //next onceRun(function() { fireing = false; _fire(); }); } else { fireing = true; } } } return self = { //增長隊列 add: function(element,options) { Queue.push(function(func) { makeAnim(element, options, func); }); //若是有一個隊列馬上觸發動畫 if(first && Queue.length ){ first = false; self.fire(); } }, //觸發 fire: function() { _fire(); } } }(); aQuery.fn = aQuery.prototype = { run:function(options){ animation.add(this.element,options); return this; } } var init = aQuery.fn.init = function(selector) { var match = rquickExpr.exec(selector); var element = document.getElementById(match[1]) this.element = element; return this; } init.prototype = aQuery.fn; return aQuery; }());