当前位置: 首页 > 图文教程 > 网络编程 > Javascript > jQuery教程:超酷的文字变色效果

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 jQuery教程:超酷的文字变色效果


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 428 ::
收藏到网摘: n/a

原作者是大名鼎鼎的Mootools和jQuery高手David Walsh,那个链接变色比较优雅一些。今天我要给大家带来一款更酷的文字变色效果。

看一下demo先.

正如你看到的那样,当你将鼠标放到文字上去的时候,文字就会变成五颜六色的。

其实这种效果来自于知名开源微博chyrp,它实现起来也并不难。基本原理是使用charAt()函数将文字打散并逐个设置字体颜色,当然,也要用到jquery的选择器和相关函数。

定义色彩数组先,这里定义了7个,当然可以定义更多。

var colors = ["#ff2e99", "#ff8a2d", "#ffe12a", "#caff2a", "#1fb5ff", "#5931ff", "#b848ff"]

核心函数:

1
2
3
4
5
6
7
8
9
10
11
12
function colorize(text) { var colorized = "" var bracket_color = "" for (i = 0; i < text.length; i++) { var index = Math.floor(Math.random()*7) if (text[i] == "(") bracket_color = colors[index] color = (bracket_color.length && (text[i] == "(" || text[i] == ")")) ? bracket_color : colors[index]//取色	colorized = colorized + '<span style="color: '+color+' !important">' + text.charAt(i) + '</span>' //重构	} return colorized
}

最后,使用jquery选择器将colorize()函数应用到相关对象上:

1
2
3
4
5
6
 $(".colorize").bind("mouseenter", function(){ $(this).data("text", $(this).text());	$(this).html(colorize($(this).text()));	}).bind("mouseleave", function(){	$(this).html($(this).data("text"));	});

这里使用了jquery的bind()函数绑定了两个事件:mouseenter和mouseleave,其实这样稍有些麻烦,我们可以简化一些,换做hover():

1
2
3
4
5
6
7
8
$(".colorize2").hover(	function(){	$(this).data("text", $(this).text());	$(this).html(colorize($(this).text()));	},	function(){	$(this).html($(this).data("text"));
});

当然,这个效果,并不是只能用于链接,只要是内容为文字的元素,都可以使用这个效果。想必这个对一般的高手,都不难吧,大家有没有更好的方法或者在其他框架上实现?请通过评论与我们分享吧!