隨機(jī)字符變換效果的jQuery插件開發(fā)教程
來源:tutorialzine.com 編譯:GBin1.com
在這篇快速的jQuery插件開發(fā)教程中,我們將創(chuàng)建一個jQuery插件用來隨機(jī)排序顯示任何一個DOM元素的文字內(nèi)容 -這將會是一個非常有趣的效果,可以用在標(biāo)題,logo及其幻燈效果中。

代碼片段
那么第一部呢,我們將開發(fā)jQuery插件的基本架構(gòu)。我們將把代碼放入一個自運(yùn)行的方法中,并且擴(kuò)展$.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);
下一步我們將關(guān)注與randomChar()方法。它將會接受一個類型參數(shù)(Lowerletter, upperletter或者symbol),并且返回一個隨機(jī)字符。
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)];
}
我們本應(yīng)該使用一個簡單的字符池來保存所有的字符,但是這樣會有更好效果。
現(xiàn)在我們來書寫插件的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);
});
};
這 個插件將可以接受被調(diào)用的DOM元素的內(nèi)容,或者當(dāng)作一個參數(shù)傳入的對象的text屬性。然后它分割字符串到字符,并且決定使用的類型。這個 shuffle功能使用setTimeout()來調(diào)用自己并且隨機(jī)生成字符串,更新DOM元素。如果你不清楚setTimeout()的使用,可以參考 這篇文章:http://www.gbin1.com/technology/jqueryhowto/fadeoutonebyone/ , 調(diào)用seTimeout方法可以幫助你按特定時間間隔執(zhí)行某些操作。
歡迎訪問GBin1.com


浙公網(wǎng)安備 33010602011771號