Simplified Version: JavaScript color gradient and gradient effect

Source: Internet
Author: User
Tags color representation getcolor

Recently I read Dean's "Convert any color value to hex in MSIE" and finally solved the problem of obtaining color rgb values based on keywords.

<! DOCTYPE html> 

Tip: the code can be modified before running!

Previous Version of JavaScript color gradient and gradient effect

Program description

ColorGrads color gradient]

The ColorGrads program is used to generate a color gradient set based on the color set and gradient level.
The gradient level refers to the number of steps to complete the gradient.

The color in web design is presented in RGB color mode.
In this mode, each color can be represented by three colors (0 to 255) representing red (r), Green (g), and blue (B.

From the w3c Colors section, we can see that the color representation in the standard includes:
Keyword format:
Em {color: red}
RGB format:
Em {color: # f00}
Em {color: # ff0000}
Em {color: rgb (255, 0, 0 )}
Em {color: rgb (100%, 0%, 0% )}
The above indicates the same color (red ).
In the form of a keyword, a keyword is used to represent a color value.
In the RGB format, the first two are mostly used. They are all "#" followed by a color value in hexadecimal notation, and the third is a color value in decimal notation, the fourth is the actual value and the percentage of 255.

Different browsers obtain different color representation formats:
"Color: red" format:
Ie opera ff chrome/safari
Style red # ff0000 red
CurrentStyle red "red"
GetComputedStyle # ff0000 rgb (255, 0, 0) rgb (255, 0, 0)
"Color: # ff0000"/"color: # f00" format:
Ie opera ff chrome/safari
Style # ff0000/# f00 # ff0000 rgb (255, 0, 0) rgb (255, 0, 0)
CurrentStyle # ff0000/# f00 # ff0000
GetComputedStyle # ff0000 rgb (255, 0, 0) rgb (255, 0, 0)
"Color: rgb (255, 0, 0)"/"color: rgb (100%, 0%, 0%)" format:
Ie opera ff chrome/safari
Style rgb (255, 0, 0) # ff0000 rgb (255, 0, 0) rgb (, 0, 0)
CurrentStyle rgb (255, 0, 0) # ff0000
GetComputedStyle # ff0000 rgb (255, 0, 0) rgb (255, 0, 0)

Basically, the obtained values are displayed in standard format, but some are automatically converted.
However, the rgb format of ie is different from that of ff/chrome/safari, and there is no space between values.
Note that the color value obtained by opera using currentStyle in the form of keyword is enclosed by double quotation marks, which is very strange and should be avoided as much as possible.

To obtain the gradient of the two colors, first convert the color to the value used for calculation.
The GetColor and GetData programs are used to convert the color values that conform to w3c standards into the red (r), Green (g), and blue (B) color values that combine the colors.
The values in the RGB format already contain the specific values of rgb. You only need to extract the values and convert them with the regular expression.
This process is performed in GetData:
Function GetData (color ){
Var re = RegExp;
If (/^ # ([0-9a-f] {2}) ([0-9a-f] {2}) ([0-9a-f] {2}) $/I. test (color )){
// # Rrggbb
Return $ A. map ([re. $1, re. $2, re. $3], function (x ){
Return parseInt (x, 16 );
});
} Else if (/^ # ([0-9a-f]) ([0-9a-f]) ([0-9a-f]) $/I. test (color )){
// # Rgb
Return $ A. map ([re. $1, re. $2, re. $3], function (x ){
Return parseInt (x + x, 16 );
});
} Else if (/^ rgb \ (. *), (. *), (. *) \) $/I. test (color )){
// Rgb (n, n, n) or rgb (n %, n %, n %)
Return $ A. map ([re. $1, re. $2, re. $3], function (x ){
Return x. indexOf ("%")> 0? ParseFloat (x, 10) * 2.55: x | 0;
});
}
}

Note: # rrggbb/# the rgb format produces hexadecimal numeric characters. If you set the second parameter of parseInt to 16, you can specify the hexadecimal format to process String Conversion.
In the format of rgb (n, n, n)/rgb (n %, n %, n %), the value is obtained directly, if % exists, calculate the corresponding value based on the percentage.
When you use this method to set the color, pay attention to the following,
Internet Explorer 6 and Internet Explorer 7 allow the use of percentages. Other values cannot be used (including Internet Explorer 8 );
Ie6 and ie7 can be separated by spaces or commas (,). Other values must be separated by commas );
Of course, we should also set it according to w3c standards.
Ps: The EM {color: rgb 1.0 0.0 0.0} written in the DHTML manual is useless and should not be misled.

If it is in the form of a keyword, you have to think of another method, you can use a dictionary object to match the color value, but this process will become very large.
Ps: here we can see the values corresponding to all color names.
Dean recently published "Convert any color value to hex in MSIE" and finally solved this problem.
The key is to use queryCommandValue ("ForeColor") to obtain the color value (perhaps familiar with the editor ).
QueryCommandValue is used to return the current value of document, range, or current selection for a given command.
The ForeColor command sets or obtains the foreground color of the text.

The specific method is to create a textarea first:
If (! Frag ){
Frag = document. createElement ("textarea ");
Frag. style. display = "none ";
Document. body. insertBefore (frag, document. body. childNodes [0]);
};
Set color to the color to be taken:
Try {frag. style. color = color;} catch (e) {return [0, 0, 0];}
If an incorrect color value is set for ie, an error is reported. Therefore, try... catch is used to ensure that the returned value can be returned.

The queryCommandValue options include document, range, and current selection.
You can use createTextRange to create a range:
Color = frag. createTextRange (). queryCommandValue ("ForeColor ");

CreateTextRange can be used in Body, Button, Input, and TextArea.
Createpopup().doc ument. body is used in dean's notebook. The advantage is that you do not need to insert elements to the dom.
However, createPopup is the ie Method, and TextArea can also be used for getComputedStyle, which will be used later.

The color value obtained in this way is a numerical value. The relationship between the number and the color is as follows:
For example, if the red hexadecimal rgb value is ff0000, convert it to bgr, that is, 0000ff, and then convert it to the 10th hexadecimal value to 255.
Similarly, pink is FFC0CB, convert to bgr is CBC0FF, and 10 is 13353215.
Ps: when using queryCommandValue ("ForeColor"), you must note that the color obtained by queryCommandValue ("ForeColor") is bgr, which is different from the general color.

To obtain the rgb value, you can reverse the conversion process. However, there are more clever methods for reference to dean's article:
Ret = [color & 0x0000ff, (color & 0x00ff00) >>> 8, (color & 0xff0000) >>> 16];
First, use the & operator to obtain the value of the corresponding bit, and then use the right shift operator (>>>) to move the value to the correct position.

For example, to obtain the green (g) color value for the pink FFC0CB, use the operation (&) to obtain the corresponding value. FFC0CB & 0x00ff00 to get the C000, then, shift 8 digits to the right to obtain C0 (a hexadecimal digit is equivalent to four digits in binary format), that is, 192.

For other documents that support document. defaultView, you can use getComputedStyle to obtain the color.
The results of obtaining color values from various browsers above show that the obtained values are in RGB format, so you can directly convert them using GetData:
Ret = GetData (document. defaultView. getComputedStyle (frag, null). color );
Note that except ff, if the element does not insert dom, the color cannot be obtained using getComputedStyle. Therefore, the element must be inserted to the body by the way when it is created.

After GetStep uses GetColor to obtain the color value, the step can be obtained based on the step:
Var colors = [], start = GetColor (start), end = GetColor (end ),
StepR = (end [0]-start [0])/step,
StepG = (end [1]-start [1])/step,
StepB = (end [2]-start [2])/step;
Generate a set based on the step size:
For (var I = 0, r = start [0], g = start [1], B = start [2]; I <step; I ++ ){
Colors [I] = [r, g, B]; r + = stepR; g + = stepG; B + = stepB;
}
Colors [I] = end;
The correct color value ranges from 0 to 255 without decimal digits. You need to correct the following:
Return $ A. map (colors, function (x) {return $ A. map (x, function (x ){
Return Math. min (Math. max (0, Math. floor (x), 255 );
});});

The program supports the continuous transformation of multiple colors:
For (var I = 0, n = len-1; I <n; I ++ ){
Var steps = GetStep (colors [I], colors [I + 1], step );
I <n-1 & steps. pop ();
Ret = ret. concat (steps );
}
Note that duplicate colors (steps. pop () must be removed from each transformation ()).

[ColorTrans color gradient]

With the color gradient set, you only need to set a timer to display the set values in turn as a gradient effect.
This gradient has two effects: The color fades in (transIn) and the color fades out (transOut ).
The principle is to change the index attribute of the _ index set to gradually increase and decrease at the time of import:
TransIn: function (){
This. stop (); this. _ index ++; this. _ set ();
If (this. _ index <this. _ colors. length-1 ){
This. _ timer = setTimeout ($ F. bind (this. transIn, this), this. speed );
}
},
TransOut: function (){
This. stop (); this. _ index --; this. _ set ();
If (this. _ index> 0 ){
This. _ timer = setTimeout ($ F. bind (this. transOut, this), this. speed );
}
},

Modify the style in the _ set settings style program:
Var color = this. _ colors [Math. min (Math. max (0, this. _ index), this. _ colors. length-1)];
This. _ elem. style [this. style] = "rgb (" + color. join (",") + ")";
The style attribute is the name of the style attribute to be modified. For example, the color is "color" and the background color is "backgroundColor ".

Because the color set is generated based on the start color, end color, and number of steps, if you want to modify these attributes, you must regenerate the set.
The reset program is used to regenerate the set, and the index is also set back to 0:
This. _ options = options =$ $. extend (this. _ options, options || {});
This. _ colors = ColorGrads ([options. from, options. to], options. step );
This. _ index = 0;

The program will also reset once during initialization:
This. reset ({
From: this. options. from | $ D. getStyle (this. _ elem, this. style ),
To: this. options.,
Step: Math. abs (this. options. step)
});
If there is no custom from color, the current color is automatically obtained.

Tips

Currently, the color of the pseudo class of the link tag a cannot be directly modified using the dom (unless the class is changed ).
So I used a small trick in the color gradient menu to change the content and jump of a to the innerHTML and onclick of td:
Var a = x. getElementsByTagName ("a") [0], href = a. href, txt = a. innerHTML;
X. onclick = function () {location. href = href ;}
X. innerHTML = txt;
In this way, the effect can be achieved without affecting availability.

An array problem was also found during the test. Run alert ([,]. length) and 3 will be returned in ie, and 2 will be returned for others.
In mozilla's Array_Literals section, find:
If you include a trailing comma at the end of the list of elements, the comma is ignored.
That is, if the array literal Element Set ends with a comma, the comma is ignored.

Instructions for use

The first parameter of ColorGrads is the color set, and the second parameter is the gradient level.

ColorTrans can set the following attributes to implement gradient objects as long as one parameter:
From: "", // start color
To: "#000", // end color
Step: 20, // gradient Series
Speed: 20, // gradient speed
Style: "color" // set attributes (Scripting attributes)
By default, from is null to facilitate automatic acquisition.
The from, to, and step parameters must be modified after instantiation using reset.
For more information, see instances.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.