原作者是大名鼎鼎的mootools和jquery高手david walsh,那個鏈接變色比較優(yōu)雅一些。今天我要給大家?guī)硪豢罡岬奈淖肿兩Ч?/p>
看一下demo先.
正如你看到的那樣,當(dāng)你將鼠標(biāo)放到文字上去的時候,文字就會變成五顏六色的。
其實這種效果來自于知名開源微博chyrp,它實現(xiàn)起來也并不難。基本原理是使用charat()函數(shù)將文字打散并逐個設(shè)置字體顏色,當(dāng)然,也要用到j(luò)query的選擇器和相關(guān)函數(shù)。
定義色彩數(shù)組先,這里定義了7個,當(dāng)然可以定義更多。
var colors = ["#ff2e99", "#ff8a2d", "#ffe12a", "#caff2a", "#1fb5ff", "#5931ff", "#b848ff"]
核心函數(shù):
123456789101112 | 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>' //重構(gòu) } return colorized} |
最后,使用jquery選擇器將colorize()函數(shù)應(yīng)用到相關(guān)對象上:
123456 | $(".colorize").bind("mouseenter", function(){ $(this).data("text", $(this).text()); $(this).html(colorize($(this).text())); }).bind("mouseleave", function(){ $(this).html($(this).data("text")); }); |
這里使用了jquery的bind()函數(shù)綁定了兩個事件:mouseenter和mouseleave,其實這樣稍有些麻煩,我們可以簡化一些,換做hover():
12345678 | $(".colorize2").hover( function(){ $(this).data("text", $(this).text()); $(this).html(colorize($(this).text())); }, function(){ $(this).html($(this).data("text"));}); |
當(dāng)然,這個效果,并不是只能用于鏈接,只要是內(nèi)容為文字的元素,都可以使用這個效果。想必這個對一般的高手,都不難吧,大家有沒有更好的方法或者在其他框架上實現(xiàn)?請通過評論與我們分享吧!
新聞熱點
疑難解答
圖片精選