jQuery中 动画渐变背景

  • 源码大小:4.99KB
  • 所需积分:1积分
  • 源码编号:19JP-3732
  • 浏览次数:711次
  • 最后更新:2023年07月16日
  • 所属栏目:其他
本站默认解压密码:19jp.com 或 19jp_com

简介

一个很小的jQuery脚本,使用线性渐变CSS函数生成动画渐变背景。

如何使用它:

1.在文档中加载所需的jQuery JavaScript库。

  1. <script src="/path/to/cdn/jquery.slim.min.js"></script>

2.为渐变背景定义一组颜色。

  1. var colors = new Array(
  2. [62,35,255],
  3. [60,255,60],
  4. [255,35,98],
  5. [45,175,230],
  6. [255,0,255],
  7. [255,128,0]
  8. );

3.动画渐变背景的主要功能。

  1. var step = 0;
  2. var colorIndices = [0,1,2,3];
  3.  
  4. var gradientSpeed = 0.002;
  5.  
  6. function updateGradient()
  7. {
  8. if ( $===undefined ) return;
  9. var c0_0 = colors[colorIndices[0]];
  10. var c0_1 = colors[colorIndices[1]];
  11. var c1_0 = colors[colorIndices[2]];
  12. var c1_1 = colors[colorIndices[3]];
  13.  
  14. var istep = 1 - step;
  15. var r1 = Math.round(istep * c0_0[0] + step * c0_1[0]);
  16. var g1 = Math.round(istep * c0_0[1] + step * c0_1[1]);
  17. var b1 = Math.round(istep * c0_0[2] + step * c0_1[2]);
  18. var color1 = "rgb("+r1+","+g1+","+b1+")";
  19.  
  20. var r2 = Math.round(istep * c1_0[0] + step * c1_1[0]);
  21. var g2 = Math.round(istep * c1_0[1] + step * c1_1[1]);
  22. var b2 = Math.round(istep * c1_0[2] + step * c1_1[2]);
  23. var color2 = "rgb("+r2+","+g2+","+b2+")";
  24.  
  25. $('#gradient').css({
  26. background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({
  27. background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});
  28. step += gradientSpeed;
  29. if ( step >= 1 )
  30. {
  31. step %= 1;
  32. colorIndices[0] = colorIndices[1];
  33. colorIndices[2] = colorIndices[3];
  34. colorIndices[1] = ( colorIndices[1] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
  35. colorIndices[3] = ( colorIndices[3] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
  36. }
  37. }

4.以给定的速度更新梯度背景。

  1. setInterval(updateGradient,10);

预览截图