在這篇快速的jQuery插件開發教程中,我們將創建一個jQuery插件用來隨機排序顯示任何一個DOM元素的文字內容 -這將會是一個非常有趣的效果,可以用在標題,logo及其幻燈效果中。
代碼片段
那么第一部呢,我們將開發jQuery插件的基本架構。我們將把代碼放入一個自運行的方法中,并且擴展$.fn.
assets/js/jquery.shuffleLetters.js
(function($){ $.fn.shuffleLetters = function(prop){ // Handling default arguments var options = $.extend({ // Default arguments },prop) return this.each(function(){ // The main plugin code goes here }); }; // A helper function function randomChar(type){ // Generate and return a random character } })(jQuery);
下一步我們將關注與randomChar()方法。它將會接受一個類型參數(Lowerletter, upperletter或者symbol),并且返回一個隨機字符。
function randomChar(type){ var pool = ""; if (type == "lowerLetter"){ pool = "abcdefghijklmnopqrstuvwxyz0123456789"; } else if (type == "upperLetter"){ pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; } else if (type == "symbol"){ pool = ",.?/\\(^)![]{}*&^%$#'\""; } var arr = pool.split(''); return arr[Math.floor(Math.random()*arr.length)]; }
我們本應該使用一個簡單的字符池來保存所有的字符,但是這樣會有更好效果。
現在我們來書寫插件的body部分:
$.fn.shuffleLetters = function(prop){ var options = $.extend({ "step" : 8, // How many times should the letters be changed "fps" : 25, // Frames Per Second "text" : "" // Use this text instead of the contents },prop) return this.each(function(){ var el = $(this), str = ""; if(options.text) { str = options.text.split(''); } else { str = el.text().split(''); } // The types array holds the type for each character; // Letters holds the positions of non-space characters; var types = [], letters = []; // Looping through all the chars of the string for(var i=0;i<str.length;i++){ var ch = str[i]; if(ch == " "){ types[i] = "space"; continue; } else if(/[a-z]/.test(ch)){ types[i] = "lowerLetter"; } else if(/[A-Z]/.test(ch)){ types[i] = "upperLetter"; } else { types[i] = "symbol"; } letters.push(i); } el.html(""); // Self executing named function expression: (function shuffle(start){ // This code is run options.fps times per second // and updates the contents of the page element var i, len = letters.length, strCopy = str.slice(0); // Fresh copy of the string if(start>len){ return; } // All the work gets done here for(i=Math.max(start,0); i < len; i++){ // The start argument and options.step limit // the characters we will be working on at once if( i < start+options.step){ // Generate a random character at this position strCopy[letters[i]] = randomChar(types[letters[i]]); } else { strCopy[letters[i]] = ""; } } el.text(strCopy.join("")); setTimeout(function(){ shuffle(start+1); },1000/options.fps); })(-options.step); }); };
這 個插件將可以接受被調用的DOM元素的內容,或者當作一個參數傳入的對象的text屬性。然后它分割字符串到字符,并且決定使用的類型。這個 shuffle功能使用setTimeout()來調用自己并且隨機生成字符串,更新DOM元素。如果你不清楚setTimeout()的使用,可以參考 這篇文章:http://www.gbin1.com/technology/jqueryhowto/fadeoutonebyone/ , 調用seTimeout方法可以幫助你按特定時間間隔執行某些操作。
【網站聲明】本站除付費源碼經過測試外,其他素材未做測試,不保證完整性,網站上部分源碼僅限學習交流,請勿用于商業用途。如損害你的權益請聯系客服QQ:2655101040 給予處理,謝謝支持。