English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Complete Example of Mouse Response Color Gradient Effect Implemented by JavaScript

This article describes the mouse response color gradient effect implemented by JavaScript. Shared for everyone's reference, as follows:

Running effect diagram as follows:

Complete code as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Color Gradient Example</title>
<script type="text/javascript">
//--------------------------------------------------------------------
//Basic class library:
//1Get object:
function $(id) {}}
  return typeof id == 'string'? document.getElementById(id): id;
  }
//2Event listener addition:
function addEventHandler(oTarget, sEventType, fnHandler) {
    if (oTarget.addEventListener) {
        oTarget.addEventListener(sEventType, fnHandler, false);
      } else if (oTarget.attachEvent) {
        oTarget.attachEvent("on"+sEventType, fnHandler);
      }) else {
        oTarget["on"+sEventType] = fnHandler;
      }
  }
//3Custom-defined 'object creation' class:
var Class = {
    Create: function() {
        return function() {
            this.initialize.apply(this, arguments);
          }
      }
  }
//4Object property merging:
Object.extend = function(destination, source) {
    for (var property in source) {
      destination[property] = source[property];
    }
    return destination;
  }
//--------------------------------------------------------------------
var colorFade = Class.Create();
colorFade.prototype = {
    //1Class initialization:
    initialize: function(obj, options){
        this._obj = $(obj);//The object that needs to change color currently.
        this._timer = null;//Timer.
        this.SetOptions(options);//The array parameter passed in.
        this.Steps = Math.abs(this.options.Steps);
        this.Speed = Math.abs(this.options.Speed);
        //this._colorArr: used to store the current color's r.g.b information.
        this.StartColorArr = this._colorArr = this.getColorArr(this.options.StartColor);
        this.EndColorArr=this.getColorArr(this.options.EndColor);
        this.EndColorArr=this.getColorArr(this.options.EndColor);
        //this.Background=this.options.Background;/The gradient values of the three primary colors (r, g, b) from start to end (that is, the amount to increase each time the gradient changes).
        The decrement value).1],this.EndColorArr[1]),this.getColorAddValue(this.StartColorArr[2],this.EndColorArr[2]);
        //Set object color:
        this._setObjColor=this.Background?function(sColor){
            this._obj.style.backgroundColor=sColor;
          }:function(sColor){
            this._obj.style.color=sColor;
          });
        this._setObjColor(this.options.StartColor);
        //Add events to the object:
        var oThis=this;
        addEventHandler(this._obj,"mouseover",
          function(){
              oThis.Fade(oThis.EndColorArr);
            }
        );
        addEventHandler(this._obj,"mouseout",function(){
            oThis.Fade(oThis.StartColorArr);
          });
      },
    /*
      2.Object property initialization:
    */
    SetOptions:function(options){
        this.options={
          StartColor:  "#000000",
          EndColor:  "#ffffff",
          Steps:    20,//Number of gradients
          Speed:    20,//Gradient speed, that is, how many milliseconds (Speed) the gradient changes every time.
          Background: true//Is it an object background gradient.
        }
        //Merge properties:
        Object.extend(this.options, options || {});
      },
    /*
      3.Get the "r.g.b" information array of a certain color:
      sColor: the color value to be calculated, formatted as "#ccc000".
      Return an array.
    */
    getColorArr: function(sColor) {
        var curColor = sColor.replace("#", "");
        var r, g, b;
        if(curColor.length >3{//Six-digit value
          r = curColor.substr(0,2);
          g = curColor.substr(2,2);
          b = curColor.substr(4,2);
        }) else {
          r = curColor.substr(0,1);
          g = curColor.substr(1,1);
          b = curColor.substr(2,1);
          r+=r;
          g+=g;
          b+=b;
        }
        //Return the 'hexadecimal' data 'decimal' value:
        return [parseInt(r,16), parseInt(g,16), parseInt(b,16);
      },
    /*
      4.Get the gradient value of the current primary color value (r.g.b) gradient.
      sRGB: the start color value (decimal)
      eRGB: the end color value (decimal)
    */
    getColorAddValue: function(sRGB, eRGB) {
      var stepValue = Math.abs((eRGB-sRGB)/this.Steps);
      if(stepValue > 0 && stepValue <1{
        stepValue =1;
      }
      return parseInt(stepValue);
    },
    /*
      5.Get the current gradient color's "r.g.b" information array.
      startColor: the starting color, formatted as "#ccc000";
      iStep: the current gradient level (i.e., the current number of gradients).
      Return color value, such as #fff000.
    */
    getStepColor: function(sColor, eColor, addValue) {
         if(sColor == eColor) {
          return sColor;
        } else if(sColor < eColor) {
          return (sColor+addValue) > eColor?eColor: (sColor+addValue);
        } else if(sColor > eColor) {
          return (sColor-addValue) < eColor?eColor: (sColor-addValue);
        }
      },
    /*
      6.Start the gradient:
      endColorArr: the target color, an array of r.g.b information.
    */
    Fade: function(endColorArr) {
         clearTimeout(this._timer);}}
        var er=endColorArr[0],
        eg=endColorArr[1],
        eb=endColorArr[2],
        r=this.getStepColor(this._colorArr[0],er,this._stepAddValueArr[0]),
        g=this.getStepColor(this._colorArr[1],eg,this._stepAddValueArr[1]),
        b=this.getStepColor(this._colorArr[2],eb,this._stepAddValueArr[2]);
        this._colorArr=[r,g,b];
        this._setObjColor("#"+Hex(r) + Hex(g) + Hex(b));
        if(r!=er||g!=eg||b!=eb){
          var oThis=this;
          oThis._timer=setTimeout(function(){oThis.Fade(endColorArr)},oThis.Speed);
        }
      }
  }
//returns16number base
function Hex(i) {
  if (i < 0) return "00";
  else if (i > 255) return "ff";
  else {
    //Decimal to Hexadecimal:
    var str = "0" + i.toString(16);
    return str.substring(str.length - 2);
  }
}
</script>
</head>
<body>
<div id="test" style="height:40px;width:200px;border:1px solid red;">
  Xixi!
</div>
<div id="test1" style="height:40px;width:200px;border:1px solid red;">
  Hohoho!
</div>
<div id="test2" style="height:40px;width:200px;border:1px solid red;">
  Haha!
</div>
</body>
<script type="text/javascript">
var colorFade01=new colorFade("test",{StartColor:'#000000',EndColor:'#8AD4FF',Background:true});
var colorFade02=new colorFade("test",{StartColor:'#8AD4FF',EndColor:'#000000',Background:false});
var colorFade03=new colorFade("test1"{StartColor:'#000000',EndColor:'#8AD4FF',Background:true});
var colorFade04=new colorFade("test1"{StartColor:'#8AD4FF',EndColor:'#000000',Background:false});
var colorFade05=new colorFade("test2"{StartColor:'#000000',EndColor:'#8AD4FF',Background:true});
var colorFade06=new colorFade("test2"{StartColor:'#8AD4FF',EndColor:'#000000',Background:false});
</script>
</html>

PS: Here are some web element style tools recommended for your reference and use:

Online Special Effects Text/Color Text Generation Tool:
http://tools.jb51.net/aideddesign/colortext

Firefox's Linear Gradients (Linear Gradient) Online Debugging Tool:
http://tools.jb51.net/aideddesign/moz_LinearGradients

webkit core safari/Chrome's Linear Gradients (Linear Gradient) Online Debugging Tool
http://tools.jb51.net/aideddesign/webkit_LinearGradients

For more content related to JavaScript, you can check out the special topics on this site: 'JavaScript OOP入门教程', 'JavaScript事件相关操作与技巧大全', 'JavaScript切换特效与技巧总结', 'JavaScript动画特效与技巧汇总', 'JavaScript错误与调试技巧总结', 'JavaScript数据结构与算法技巧总结', and 'JavaScript数学运算用法总结'

I hope the content described in this article will be helpful to everyone in designing JavaScript programs.

Statement: The content of this article is from the Internet, the copyright belongs to the original author, the content is contributed and uploaded by Internet users spontaneously, this website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like