本文實例講述了jQuery實現的背景顏色漸變動畫效果。分享給大家供大家參考,具體如下:
完整實例代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>背景顏色漸變</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
</head>
<body>
<input id="Button1" type="button" value="button" onclick="tggg()" />
<script>
function tggg() {
//$("#asd").css({ "background-color": "red" }).show().fadeOut(500);
fadeColor(
{ r: 0, g: 255, b: 0 }, //star color
{r: 255, g: 255, b: 255 }, //end color
function (color) { document.getElementById("asd").style.backgroundColor = color; }, 1, 10);
}
//所有代碼的執行時間只有24毫秒左右。
function fadeColor(from, to, callback, duration, totalFrames) {
//用一個函數來包裹setTimeout,根據幀數來確定延時
function doTimeout(color, frame) {
setTimeout(function () {
try {
callback(color);
} catch (e) { JSLog.write(e); }
}, (duration * 1000 / totalFrames) * frame);
//總持續秒數/每秒幀數*當前幀數=延時(秒),再乘以1000作為延時(毫秒)
}
// 整個漸變過程的持續時間,默認為1秒
var duration = duration || 1;
// 總幀數,默認為持續秒數*15幀,也即每秒15幀
var totalFrames = totalFrames || duration * 15; var r, g, b; var frame = 1;
//在第0幀設置起始顏色
doTimeout('rgb(' + from.r + ',' + from.g + ',' + from.b + ')', 0);
//計算每次變化所需要改變的rgb值
while (frame < totalFrames + 1) {
r = Math.ceil(from.r * ((totalFrames - frame) / totalFrames) + to.r * (frame / totalFrames));
g = Math.ceil(from.g * ((totalFrames - frame) / totalFrames) + to.g * (frame / totalFrames));
b = Math.ceil(from.b * ((totalFrames - frame) / totalFrames) + to.b * (frame / totalFrames));
// 調用本frame的doTimeout
doTimeout('rgb(' + r + ',' + g + ',' + b + ')', frame); frame++;
}
}
</script>
<div style="width: 600px; height: 200px; border: 1px solid red;" id="asd">
歡迎各位光臨--http://www.jb51.net
</div>
</body>
</html>
PS:這裡再為大家推薦幾款相關的顏色與特效工具供大家參考使用:
在線特效文字/彩色文字生成工具:
http://tools.jb51.net/aideddesign/colortext
在線彩虹文字/顏色漸變文字生成工具:
http://tools.jb51.net/aideddesign/txt_caihongzi
在線發光字生成工具:
http://tools.jb51.net/aideddesign/txt_faguangzi
仿古書排版文字豎排轉換工具:
http://tools.jb51.net/transcoding/shupai
更多關於jQuery相關內容感興趣的讀者可查看本站專題:《jQuery常用插件及用法總結》、《jquery中Ajax用法總結》、《jQuery表格(table)操作技巧匯總》、《jQuery擴展技巧總結》、《jQuery常見經典特效匯總》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程序設計有所幫助。