Home Web Front-end JS Tutorial A complete example of mouse response color gradient effect implemented in JavaScript

A complete example of mouse response color gradient effect implemented in JavaScript

Feb 20, 2017 pm 04:43 PM

This article mainly introduces the mouse response color gradient effect implemented by JavaScript, involving JavaScript object-oriented and event monitoring, response mechanism-related operating skills. Friends in need can refer to the following

The example of this article describes the JavaScript implementation The mouse responds to the color gradient effect. Share it with everyone for your reference, the details are as follows:

The running effect diagram is as follows:

A complete example of mouse response color gradient effect implemented in JavaScript

The complete code is 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>颜色渐变实例</title>
<script type="text/javascript">
//--------------------------------------------------------------------
//基础类库:
//1.获取对象:
function $(id){
  return typeof id==&#39;string&#39;?document.getElementById(id):id;
  }
//2.添加事件监听:
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;
      }
  }
//3.自定"义产生对象"类:
var Class={
    Create:function(){
        return function(){
            this.initialize.apply(this,arguments);
          }
      }
  }
//4.对象属性合并:
Object.extend=function(destination,source){
    for(var property in source){
      destination[property]=source[property];
    }
    return destination;
  }
//--------------------------------------------------------------------
var colorFade=Class.Create();
colorFade.prototype={
    //1.类的初始化:
    initialize:function(obj,options){
        this._obj=$(obj);//当前要改变颜色的对象。
        this._timer=null;//计时器。
        this.SetOptions(options);//传入的数组参数。
        this.Steps=Math.abs(this.options.Steps);
        this.Speed=Math.abs(this.options.Speed);
        //this._colorArr:用来寄存当前颜色的r.g.b信息。
        this.StartColorArr=this._colorArr=this.getColorArr(this.options.StartColor);
        this.EndColorArr=this.getColorArr(this.options.EndColor);
        this.Background=this.options.Background;
        //从开始到结束,r.g.b三种原色渐变的梯度值(即,每次渐变要增加/减少的值)。
        this._stepAddValueArr=[this.getColorAddValue(this.StartColorArr[0],this.EndColorArr[0]),this.getColorAddValue(this.StartColorArr[1],this.EndColorArr[1]),this.getColorAddValue(this.StartColorArr[2],this.EndColorArr[2])];
        //设置对象颜色:
        this._setObjColor=this.Background?function(sColor){
            this._obj.style.backgroundColor=sColor;
          }:function(sColor){
            this._obj.style.color=sColor;
          };
        this._setObjColor(this.options.StartColor);
        //为对象添加事件:
        var oThis=this;
        addEventHandler(this._obj,"mouseover",
          function(){
              oThis.Fade(oThis.EndColorArr);
            }
        );
        addEventHandler(this._obj,"mouseout",function(){
            oThis.Fade(oThis.StartColorArr);
          });
      },
    /*
      2.对象属性初始化:
    */
    SetOptions:function(options){
        this.options={
          StartColor:  "#000000",
          EndColor:  "#ffffff",
          Steps:    20,//渐变次数
          Speed:    20,//渐变速度,即每隔多少(Speed)毫秒渐变一次。
          Background: true//是否为对象背景渐变。
        }
        //合并属性:
        Object.extend(this.options,options||{});
      },
    /*
      3.得到某个颜色的"r.g.b"信息数组:
      sColor:被计算的颜色值,格式为"#ccc000"。
      返回的一个数组。
    */
    getColorArr:function(sColor){
        var curColor=sColor.replace("#","");
        var r,g,b;
        if(curColor.length>3){//六位值
          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 [parseInt(r,16),parseInt(g,16),parseInt(b,16)];
      },
    /*
      4.得到当前原色值(r.g.b)渐变的梯度值。
      sRGB:开始颜色值(十进制)
      eRGB:结束的颜色值(十进制)
    */
    getColorAddValue:function(sRGB,eRGB){
      var stepValue=Math.abs((eRGB-sRGB)/this.Steps);
      if(stepValue>0&&stepValue<1){
        stepValue=1;
      }
      return parseInt(stepValue);
    },
    /*
      5.得到当前渐变颜色的"r.g.b"信息数组。
      startColor:开始的颜色,格式为"#ccc000";
      iStep:当前渐变的级数(即当前渐变的次数)。
      返回颜色值,如 #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.开始渐变:
      endColorArr:目标颜色,为r.g.b信息数组。
    */
    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);
        }
      }
  }
//返回16进制数
function Hex(i) {
  if (i < 0) return "00";
  else if (i > 255) return "ff";
  else {
    //十进制 转成 十六进制:
    var str = "0" + i.toString(16);
    return str.substring(str.length - 2);
  }
}
</script>
</head>
<body>
<p id="test" style="height:40px;width:200px;border:1px solid red;">
  嘻嘻!
</p>
<p id="test1" style="height:40px;width:200px;border:1px solid red;">
  呵呵!
</p>
<p id="test2" style="height:40px;width:200px;border:1px solid red;">
  哈哈!
</p>
</body>
<script type="text/javascript">
var colorFade01=new colorFade("test",{StartColor:&#39;#000000&#39;,EndColor:&#39;#8AD4FF&#39;,Background:true});
var colorFade02=new colorFade("test",{StartColor:&#39;#8AD4FF&#39;,EndColor:&#39;#000000&#39;,Background:false});
var colorFade03=new colorFade("test1",{StartColor:&#39;#000000&#39;,EndColor:&#39;#8AD4FF&#39;,Background:true});
var colorFade04=new colorFade("test1",{StartColor:&#39;#8AD4FF&#39;,EndColor:&#39;#000000&#39;,Background:false});
var colorFade05=new colorFade("test2",{StartColor:&#39;#000000&#39;,EndColor:&#39;#8AD4FF&#39;,Background:true});
var colorFade06=new colorFade("test2",{StartColor:&#39;#8AD4FF&#39;,EndColor:&#39;#000000&#39;,Background:false});
</script>
</html>
Copy after login

For more complete examples of mouse response color gradient effects implemented in JavaScript, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles