js The Yellow Fade Technique
2012-10-28 21:57 youxin 阅读(300) 评论(0) 编辑 收藏 举报http://37signals.com/svn/archives/000558.php
http://www.cnblogs.com/QLeelulu/archive/2008/03/25/1120854.html
效果请将鼠标移到任意的链接上就能看到 下面直接看代码: fadeUp=function(element,red,green,blue){ if(element.fade){ window.clearTimeout(element.fade); } var cssValue = "rgb("+red+","+green+","+blue+")"; element.style.backgroundColor = cssValue; //$(element).css("background-color",cssValue); if(red == 255 && green == 255 && blue == 255){ return; } var newRed = red + Math.ceil((255-red)/10); var newGreen = green + Math.ceil((255-green)/10); var newBlue = blue + Math.ceil((255-blue)/10); var repeat = function(){ fadeUp(element,newRed,newGreen,newBlue); }; element.fade=window.setTimeout(repeat,100); } 好,我们来分析一下代码. 背景色用 rgb(red, green, blue) 来设置. 然后用到了一个递归的调用: var repeat = function(){ fadeUp(element,newRed,newGreen,newBlue); }; 递归的结果是背景色的值趋向#ffffff,也就是白色. 递归是通过 setTimeout(function(),time) 这个函数设置延时来实现的.这个函数的意思是每隔time时间片后就执行function()函数.后面的time的单位是毫秒. clearTimeout()用于清除这个延时.
上面代码不理解可以看:http://www.cnblogs.com/youxin/archive/2012/08/28/2660443.html
另一个:
<!doctype html> <html> <head> <title>The Yellow Fade Technique in pure JavaScript</title> <style type="text/css"> body { background-color: blue; color: black; } </style> </head> <body> <h1>The Yellow Fade Technique in pure JavaScript</h1> <p id="yft">Click the button to show the Yellow Fade Technique on this paragraph.</p> <p><button>Fade</button></p> <script> YFT = { fade: function(element, startcolour, endcolour, time_elapsed) { var interval = 30; var steps = time_elapsed / interval; var red_change = (startcolour[0] - endcolour[0]) / steps; var green_change = (startcolour[1] - endcolour[1]) / steps; var blue_change = (startcolour[2] - endcolour[2]) / steps; var currentcolour = startcolour; var stepcount = 0; element.style.backgroundColor = 'rgb(' + currentcolour.toString() + ')'; var timer = setInterval(function(){ currentcolour[0] = parseInt(currentcolour[0] - red_change); currentcolour[1] = parseInt(currentcolour[1] - green_change); currentcolour[2] = parseInt(currentcolour[2] - blue_change); element.style.backgroundColor = 'rgb(' + currentcolour.toString() + ')'; stepcount += 1; if (stepcount >= steps) { element.style.backgroundColor = 'rgb(' + endcolour.toString() + ')'; clearInterval(timer); } }, interval); }, click: function() { YFT.fade(document.getElementById("yft"), [255,255,60], [0,0,255], 750); return false; } } document.getElementsByTagName("button")[0].onclick = YFT.click; </script> </body> </html>
演示:http://devfiles.myopera.com/articles/622/yft_pure_js.html