您的位置:首页 > Web前端 > JQuery

随机字符变换效果的jQuery插件开发教程

2011-10-22 00:00 501 查看
来源:tutorialzine.com 编译:GBin1.com

在这篇快速的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方法可以帮助你按特定时间间隔执行某些操作。

原文来自:随机字符变换效果的jQuery插件开发教程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: