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

Vollständiges Beispiel der Farbveränderungseffekt durch Mausereignis in JavaScript

本文实例讲述了JavaScript实现的鼠标响应颜色渐变效果。分享给大家供大家参考,具体如下:

运行效果图如下:

完整代码如下:

<!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 == 'string'?document.getElementById(id):id;
  }
//2Eventlistener hinzufügen:
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;
      }
  }
//3Selbstdefinierte "Objektproduktion"-Klasse:
var Class = {
    Create: function() {
        return function() {
            this.initialize.apply(this, arguments);
          }
      }
  }
//4Objektattributkombination:
Object.extend = function(destination, source) {
    for (var property in source) {
      destination[property] = source[property];
    }
    return destination;
  }
//--------------------------------------------------------------------
var colorFade = Class.Create();
colorFade.prototype = {
    //1Klasseninitialisierung:
    initialize: function(obj, options){
        this._obj = $(obj);//Das aktuelle Objekt, dessen Farbe geändert werden soll.
        this._timer = null;//Zeitgeber.
        this.SetOptions(options);//Übergabeparameter in Form eines Arrays.
        this.Steps = Math.abs(this.options.Steps);
        this.Speed = Math.abs(this.options.Speed);
        //this._colorArr: dient dazu, die r.g.b-Informationen der aktuellen Farbe zu speichern.
        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;/Gradient values of r, g, b three primary colors from start to end (that is, the amount to increase each time the gradient changes).
        Reduced 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 event to 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 (Speed) milliseconds the gradient changes each time.
          Background: true//Is the object background gradient.
        }
        //Merge properties:
        Object.extend(this.options, options || {});
      },
    /*
      3.Erhalten der "r.g.b"-Informationen einer Farbe:
      sColor: Berechneter Farbwert, Format "#ccc000".
      Rückgabe eines Arrays.
    */
    getColorArr: function(sColor) {
        var curColor = sColor.replace("#", "");
        var r, g, b;
        if(curColor.length >3){//Sechsstellige Werte
          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;
        }
        //Rückgabe des "Hexadezimal"-Datenwertes im "Dezimal"-Wert:
        return [parseInt(r,16), parseInt(g,16), parseInt(b,16]);
      },
    /*
      4.Erhalten des Gradientenwerts der aktuellen Grundfarbveränderung (r.g.b).
      sRGB: Anfangsfarbe (Dezimalwert)
      eRGB: Ziel-Farbe (Dezimalwert)
    */
    getColorAddValue: function(sRGB, eRGB) {
      var stepValue = Math.abs((eRGB-sRGB)/this.Steps);
      if(stepValue > 0 && stepValue <1){
        stepValue =1;
      }
      return parseInt(stepValue);
    },
    /*
      5.Erhalten der "r.g.b"-Informationen der aktuellen Farbveränderung.
      startColor: Die Anfangsfarbe, Format "#ccc000";
      iStep: Der aktuelle Farbveränderungsgrad (d.h. die aktuelle Anzahl der Farbveränderungen).
      Rückgabe des Farbwertes, z.B. #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 der Farbveränderung:
      endColorArr: ZielFarbe, ein Array mit r.g.b-Informationen.
    */
    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>
<div id="test" style="height:40px;width:200px;border:1px solid red;">
  嘻嘻!
</div>
<div id="test1" style="height:40px;width:200px;border:1px solid red;">
  呵呵!
</div>
<div id="test2" style="height:40px;width:200px;border:1px solid red;">
  哈哈!
</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: Hier einige weitere Tools zu den Stilen von Web-Elementen zur Referenz und Verwendung vorgeschlagen:

Online-Effekttexte/Werkzeug zur Erstellung farbiger Texte:
http://tools.jb51.net/aideddesign/colortext

Online-Debugging-Tool für Linear Gradients (Linear-Verläufe) von Firefox:
http://tools.jb51.net/aideddesign/moz_LinearGradients

webkit-Kern safari/Online-Debugging-Tool für Linear Gradients (Linear-Verläufe) von Chrome
http://tools.jb51.net/aideddesign/webkit_LinearGradients

Mehr über JavaScript finden Sie in den Themenbereichen dieser Website: 'Einführung in die objektorientierte Programmierung mit JavaScript', 'Vollständiges Handbuch zu JavaScript-Events und Techniken', 'Zusammenfassung von Animationseffekten und -techniken mit JavaScript', 'Zusammenfassung von Fehlerbehandlungs- und Debugging-Techniken mit JavaScript', 'Zusammenfassung von Datenstrukturen und Algorithmen mit JavaScript' und 'Zusammenfassung der Verwendung von Mathematikoperationen in JavaScript'.

Ich hoffe, dass die in diesem Artikel beschriebenen Inhalte für Ihre JavaScript-Programmgestaltung von Vorteil sind.

Erklärung: Der Inhalt dieses Artikels wurde aus dem Internet übernommen und gehört dem jeweiligen Urheber. Der Inhalt wurde von Internetnutzern freiwillig beigesteuert und hochgeladen. Diese Website besitzt keine Eigentumsrechte und hat den Inhalt nicht von Hand bearbeitet. Sollten Sie urheberrechtlich geschützte Inhalte finden, sind Sie herzlich eingeladen, eine E-Mail an notice#w zu senden.3codebox.com (Bitte ersetzen Sie # durch @, wenn Sie eine Meldung senden, und fügen Sie relevante Beweise bei. Bei nachgewiesener Täuschung wird diese Website die fraglichen urheberrechtlichen Inhalte sofort löschen.)

Gefällt mir