昨天,本來這篇文章是要推到博客園首頁的,但是管理員發郵件說,博文應當以分享知識為主,不應該只貼代碼,想想覺得很對,就打算重新整理一下這篇文章。
剛才在安裝visual studio 12,發現它的安裝界面都是win8風格的,而且安裝的時候有個進度條,看着挺不錯,就用 jquery 實現了一下,的確挺有趣:
先說說原理吧!進度條里面的小球運動分成 3 個階段,減速(-10px ~ 190px),勻速(190px ~ 310px),加速(310px ~ 510px)。上面的黑色框總寬度為 500 像素,小球(寬高均為 10 像素)在運動的時候,首先從 -10px 的地方起步,然后快速的到達 190px 的地方,然后再勻速的到達 310px 的地方, 最后加速到達末尾 510px 的地方。小球每一次的運動都是 jquery.animate 來實現的,每次運動完畢會觸發一個回調函數,回調函數根據小球的位置決定小球下一階段的運動過程,並且讓小球持續保持運行。詳細請參考代碼注釋。
代碼:
<!DOCTYPE html> <html> <head> <style type="text/css"> * {margin:0;padding:0} .progress {width:500px;height:100px;margin:0 auto;position:relative;background-color: #000;overflow:hidden;} .progress .btn {display:block;position:absolute;width:100px;height:30px;text-align:center;line-height:30px;color:#FFF;font-size:16px;cursor: pointer;border:1px solid #000;} .progress .btn:hover {border-color:#EEE;} .star {width:10px;height:10px;border-radius:5px;background-color: #92C4E6;position:absolute;left:-10px;top:45px;} </style> <script type="text/javascript" src="jquery/jquery.js"></script> <script type="text/javascript"> $(function(){
//效果的運行通過按鈕觸發,此函數即為點擊按鈕之后執行的回調函數 var anim = function(){ var that = $(this), thatp = that.parent();
//2. 按鈕自身的動畫,點擊之后,跑到容器的右下角,並改變文字,完畢之后,開始運行進度條 that.animate({left:thatp.width()-that.width(),top:thatp.height()-that.height()}, "fast", function(){ var i = 200;
//解綁原有的的 click 回調函數,並重新綁定 $(".progress").children("a").text("點擊停止效果").unbind("click").bind("click", function(){ var that = $(this), thatp = that.parent();
//停止小球動畫並將所有的 div 移除 $(this).closest(".progress").children(".star").stop().remove();
//按鈕復位 $(this).animate({left: (thatp.width()-that.width())/2, top: (thatp.height()-that.height())/2}, "slow", function(){ $(".progress").children("a").text("點擊觀看效果"); }).unbind('click').bind('click', anim); //重新綁定
//在按鈕之后添加 5 個 div ,並將當前 jquery 內部棧退回到只含有 ['.progress'],然后迭代每一個 div }).after(new Array(6).join('<div class="star"></div>')).end().children(".star").each(function(){
//小球每次運動完畢執行的回調函數,使用 $.proxy 綁定回調函數中的 this 為當前元素 var callback = $.proxy(function(){ var that = $(this), left = parseInt(that.css("left")); //解析當前元素的 left 位置 if(left === 510) { left = -10;that.css("left", left); } //如果已經到達末尾,重置為起點 switch(left) { case -10:
//這里本來使用的是 jquery.ui.effect.js 里面的 easeInCubic,為了精簡代碼放棄了 that.animate({left: 190}, 700, 'swing', callback); break; case 190: that.animate({left: 310}, 1500, 'linear', callback); break; case 310:
//這里本來使用的是 jquery.ui.effect.js 里面的 easeOutCubic,為了精簡代碼放棄了 that.animate({left: 510}, 700, 'swing', callback).delay(1000);
break;
}
}, this);
setTimeout(callback, i); i +=200;
}); }); }, p, a;
//貌似博客園不能再博文里面寫 HTML,JS 代碼,所以只好自己構造 DOM, p = $(".progress").html('<a class="btn">點擊觀看效果</a>');
//1. 綁定按鈕 click 事件 a = p.children('a').bind('click', anim);
//將按鈕置於容器的中間 a.css({left: (p.width()-a.width())/2, top: (p.height()-a.height())/2}); }); </script> </head> <body> <div class="progress"></div> </body> </html>