JavaScript linear gradient Two _javascript tips

Source: Internet
Author: User
Tags hasownproperty
First of all, ie, this is the largest user base, if this part of the development does not come out, the basic can be said not to do. IE has the gradient filter, but compared to other browsers, the implementation is very weak, no multiple gradients (Stop-color), can not achieve angular gradient, but also often invalid. My idea is this, if there is a text div, to achieve multiple linear gradient, we first have to take out the text inside it, and then put a few div, a few weight on a few, and then put them to the gradient. If it is a vertical gradient, this is good to do, nothing to do, just set its filters with each of the job line. If horizontal, let it float or absolute position, put it in the right place, set its filter and width. The gradient filter, however, fails after the float or after positioning, which is unheard of when using a transparent filter. There is no way to sacrifice the ancient artifact table. However, when set to long and wide, using the style to set is not working, be sure to use the DOM attribute. The gradient is owned by its TD element. In order to remove between the table element and the TD element, the TD element and its content between the blank, we also need to use cellpadding and cellspacing.
<!doctype html> <title>javascript linear gradient by Masaki </title> <meta charset= "Utf-8"/> <meta name= " Keywords "content=" javascript linear gradient by Masaki "/> <meta name=" description "content=" JavaScript linear gradient by Masaki "/> < Style type= "Text/css" > #gradient {width:800px; height:200px; border:1px solid red; } </style> <script type= "Text/javascript" >//④ use IE filter to implement gradient function SetFilter (el,start,end,type) {El.style. Filter = "Progid:DXImageTransform.Microsoft.Gradient (enabled= ' true ', startcolorstr=" +start+ ", gradienttype=" +type+ ") ", endcolorstr=" +end+ ")"; //③ the implementation of each gradient body, is the table or div function createstop (parent,top,left,width,height,type) {if (type) {var table = Document.crea Teelement ("table"); Parent.appendchild (table); var tr = table.insertrow (0), TD = Tr.insertcell (0) table.height = height+ "px"; Table.width = width+ "px"; table.cellpadding = 0; table.cellspacing = 0; Table.style.cssText = "Position:absolute;top:" +top+ "Px;left:" +left+ "PX" TD.InnerHTML = ""; return TD; var div = document.createelement ("div"); Parent.appendchild (DIV); Div.style.height = height+ "px"; Div.style.width = width+ "px"; return div; //② the concrete implementation of the gradient, determine how many gradient bodies to use, the color of each gradient (whether it is gradient or solid) and the long width coordinate var iegradient = function (entity,stops,width,height,type) {var offset , Color,beforecolor,stopwidth,stopheight,left,top,stop; for (Var i=0,j=0,l=stops.length;i<l;i++,j++) {offset = Stops[i].split (",") [0]; color = Stops[i].split (",") [1]; Stopwidth = (offset/100 * width). toFixed (1); Stopheight = (offset/100 * height). toFixed (1); switch (i) {case 0:beforecolor = color; left = Stopwidth; top = stopheight; if (offset!= 0) {//Insert a solid-colored table stop = type? Createstop (Entity,0,0,stopwidth,height,type): Createstop (entity,0,0,width , Stopheight,type); Stop.style.backgroundColor = color; } break; Case L-1://First insert a gradient table var w2 = (100-offset)/100 * width). toFixed (1), H2 = ((100-offset)/100 * height). toFixed (1), Stop = type? Createstop (Entity,0,left,widtH-left-w2,height,type): Createstop (Entity,0,0,width,height-top-h2,type); SetFilter (Stop,beforecolor,color,type); if (offset!= 100) {//Then insert a solid-colored table var stop2 = type? Createstop (Entity,0,stopwidth,w2,height,type): Createstop (entity,0 , 0,width,h2,type); Stop2.style.backgroundColor = color; } break; Default://Insert a gradient of table stop = type? Createstop (Entity,0,left,stopwidth-left,height,type): Createstop (Entity,0,0,width,stopheight-top,type); SetFilter (Stop,beforecolor,color,type); Beforecolor = color; left = Stopwidth; top = stopheight; Break //① Gradient's principal function var gradient = function (id) {var entity = document.getElementById (id), options = Arguments[1] | | {}, Width = options.width, height = options.height, type = options.type, stops = options["Color-stop"]; Entity.style.position = "relative"; var content = entity.innerhtml; entity.innerhtml = ""; Make a gradient to the target object. Iegradient (Entity,stops,width,height,type); The target object to rejoin the original content. var contentdiv = document. createelement ("div"); ContentDiv.style.cssText = "position:absolute;top:0;left:0"; contentdiv.innerhtml = content; Entity.appendchild (CONTENTDIV); } window.onload = function () {gradient ("gradient", {width:800,height:200,type:1, color-stop): ["0,red", "16,orange", "" 32,yellow "," 48,green "," 64,blue "," 80,indigo "," 100,violet "})} </script> <div id=" Gradient "> JavaScript linear gradient by Shizhong to achieve multiple horizontal gradient effects </div> <p "> must be in IE to see the effect!" </p>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Safari,chrome and opera are intended to be implemented using SVG. To reduce the length of the function, two auxiliary functions were deliberately made.
Copy Code code as follows:

var createsvg = function (tag) {
Return Document.createelementns ("Http://www.w3.org/2000/svg", tag);
};
var attr= function (node,bag) {
for (var i in bag) {
if (Bag.hasownproperty (i))
Node.setattribute (I,bag[i])
}
};
var cosgradient = function (Entity,stops,width,height,type) {
var svg = createsvg ("svg");
attr (svg,{width:width+ "px", height:height+ "px"})
Entity.appendchild (SVG);
.
var defs = createsvg ("defs");
Svg.appendchild (defs);
var lineargradient = createsvg ("LinearGradient");
Defs.appendchild (lineargradient);
attr (lineargradient,{id: "Nasami", X1: "0%", y1: "0%"})
if (type) {
attr (lineargradient,{x2: "100%", y2: "0%"})
}else{
attr (lineargradient,{x2: "0%", y2: "100%"})
}
for (Var i=0,j=0,l=stops.length;i<l;i++,j++) {
var offset = Stops[i].split (",") [0] + "%",
color = Stops[i].split (",") [1],
Stop = Createsvg ("Stop");
attr (Stop,{offset:offset, "Stop-color": color});
Lineargradient.appendchild (stop);
}
var rect = createsvg ("rect");
Svg.appendchild (rect);
attr (rect,{x: "0px", Y: "0px", width:width+ "px", height:height+ "px", fill: "URL (#nasami)"});
}

Firefox uses its private properties:
Copy Code code as follows:

var ffgradient= function (Entity,stops,width,height,type) {
var csstext = "; Background:-moz-linear-gradient ("
Csstext + = type? "Top,bottom,": "Left,right,";
.
for (Var i=0,j=0,l=stops.length;i<l;i++,j++) {
var offset = Stops[i].split (",") [0] + "%",
color = Stops[i].split (",") [1];
Csstext + = "Color-stop (" +[offset,color]+ "),"
}
Csstext = Csstext.replace (/,$/, "") + ") no-repeat;";
Entity.style.cssText = csstext+ "width:" +width+ "Px;height:" +height+ "PX;"
}

Today, however, I found that Firefox still supports the linear gradient of SVG, so correct my original point of view. The above function is just a means of implementing it here, and it's not integrated into my final version (although it's much shorter than SVG implementations). As a result, we can also achieve linear gradients in older versions of Firefox.
The gradient effect in the following box will work in all major browsers.
<!doctype html> <title>javascript linear gradient by Masaki </title> <meta charset= "Utf-8"/> <meta name= " Keywords "content=" javascript linear gradient by Masaki "/> <meta name=" description "content=" JavaScript linear gradient by Masaki "/> < Style type= "Text/css" > #gradient {width:800px; height:100px; border:1px solid red; } </style> <script type= "Text/javascript" > var attr= function (node,bag) {for (var i in bag) {if (Bag.hasown Property (i)) Node.setattribute (I,bag[i])}}; ④ use IE filter to implement gradient function SetFilter (el,start,end,type) {el.style.filter = "progid:DXImageTransform.Microsoft.Gradient" ( Enabled= ' true ', startcolorstr= "+start+", gradienttype= "+type+", endcolorstr= "+end+") "; //③ the implementation of each gradient body, is the table or div function createstop (parent,top,left,width,height,type) {if (type) {var table = Document.crea Teelement ("table"); Parent.appendchild (table); var tr = table.insertrow (0), TD = Tr.insertcell (0) attr (table,{height:height+ "px", width:width+ "px", Cellpadding:0,cellspacing:0}) CSS (table,{position: "Absolute", top:top+ "px", left:left+ "px"}); td.innerhtml = ""; return TD; var div = document.createelement ("div"); Parent.appendchild (DIV); CSS (div,{height:height+ "px", width:width+ "px"}) return div; }; var createsvg = function (tag) {return Document.createelementns ("Http://www.w3.org/2000/svg", tag); }; var css = function (node,bag) {var str = ";" for (var i in bag) {if (Bag.hasownproperty (i)) str + = i+ ": +bag[i]+";} Node.style.cssText = str; var svggradient = function (entity,stops,width,height,type) {var svg = createsvg ("svg"); attr (svg,{width:width+ "px", height:height+ "px"}) entity.appendchild (SVG); var defs = createsvg ("defs"); Svg.appendchild (defs); var lineargradient = createsvg ("LinearGradient"); Defs.appendchild (lineargradient); attr (lineargradient,{id: "Nasami", X1: "0%", y1: "0%"}) if (type) {attr (lineargradient,{x2: "100%", y2: "0%"})}else{attr ( LINEARGRADIENT,{X2: "0%", y2: "100%"})} for (Var i=0,j=0,l=stops.length;i<l;i++,j++) {var offset = Stops[i].split (",") [0] + "%", color = Stops[i].split (",") [1], stop = createsvg ("Stop"); attr (Stop,{offset:offset, "Stop-color": color}); Lineargradient.appendchild (stop); var rect = createsvg ("rect"); Svg.appendchild (rect); attr (rect,{x: "0px", Y: "0px", width:width+ "px", height:height+ "px", fill: "URL (#nasami)"}); //② the concrete implementation of the gradient, determine how many gradient bodies to use, the color of each gradient (whether it is gradient or solid) and the long width coordinate var iegradient = function (entity,stops,width,height,type) {var offset , Color,beforecolor,stopwidth,stopheight,left,top,stop; for (Var i=0,j=0,l=stops.length;i<l;i++,j++) {offset = Stops[i].split (",") [0]; color = Stops[i].split (",") [1]; Stopwidth = (offset/100 * width). toFixed (1); Stopheight = (offset/100 * height). toFixed (1); switch (i) {case 0:beforecolor = color; left = Stopwidth; top = stopheight; if (offset!= 0) {//Insert a solid-colored table stop = type? Createstop (Entity,0,0,stopwidth,height,type): Createstop (entity,0,0,width , Stopheight,type); CSS (Stop,{background:color}); } break; CasE L-1://First insert a gradient table var w2 = (100-offset)/100 * width). toFixed (1), H2 = ((100-offset)/100 * height). toFixed (1), St op = type? Createstop (Entity,0,left,width-left-w2,height,type): Createstop (Entity,0,0,width,height-top-h2,type); SetFilter (Stop,beforecolor,color,type); if (offset!= 100) {//Then insert a solid-colored table var stop2 = type? Createstop (Entity,0,stopwidth,w2,height,type): Createstop (entity,0 , 0,width,h2,type); CSS (Stop2,{background:color}); } break; Default://Insert a gradient of table stop = type? Createstop (Entity,0,left,stopwidth-left,height,type): Createstop (Entity,0,0,width,stopheight-top,type); SetFilter (Stop,beforecolor,color,type); Beforecolor = color; left = Stopwidth; top = stopheight; Break //① Gradient's principal function var gradient = function (id) {var entity = document.getElementById (id), options = Arguments[1] | | {}, Width = options.width, height = options.height, type = options.type, stops = options["Color-stop"]; CSS (entity,{position: "Relative"}); var CoNtent = entity.innerhtml; entity.innerhtml = ""; !+ "\v1"? Iegradient (Entity,stops,width,height,type): Svggradient (entity,stops,width,height,type) var contentDiv = Document.createelement ("div"); CSS (contentdiv,{position: "Absolute", top:0,left:0}) contentdiv.innerhtml = content; Entity.appendchild (CONTENTDIV); } window.onload = function () {gradient ("gradient", {width:800,height:100,type:1, color-stop): ["0,red", "16,orange", "" 32,yellow "," 48,green "," 64,blue "," 80,indigo "," 100,violet "})} </script> <div id=" Gradient "> JavaScript linear gradient by Shizhong to achieve multiple horizontal gradient effects </div> https://developer.mozilla.org/en/SVG/Tutorial/Fill_Stroke_and_Gradients
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

and make it into a class. Briefly: its first argument is IE, and the second is hash. Hash parameters are required, width,height units are px;type 0 or 1, 0 for vertical, 1 for horizontal; Color-stop represents the gradient body, consisting of an array of strings, each of which is composed of a numeric comma plus a color value, a numeric offset, The unit is%, the color value can be a noun such as red,green, or it can be a six-bit or three-bit hash value. The gradient body must have at least one.
Copy Code code as follows:

New gradient ("gradient", {width:800,height:100,type:0, "color-stop": ["0,red",
3. "16,orange", "32,yellow", "48,green", "64,blue", "80,indigo", "100,violet"]}

<!doctype html> <title>javascript linear gradient by Masaki </title> <meta charset= "Utf-8"/> <meta name= " Keywords "content=" javascript linear gradient by Masaki "/> <meta name=" description "content=" JavaScript linear gradient by Masaki "/> < Style type= "Text/css" > gradient{width:800px; height:100px; } </style> <script type= "Text/javascript" > var gradient = function (id) {var entity = Document.getelementby ID (ID), options = Arguments[1] | | {}, Width = options.width, height = options.height, type = options.type, stops = options["Color-stop"]; This.init (Entity,stops,width,height,type); } gradient.prototype ={constructor:gradient, Init:function (entity,stops,width,height,type) {this.css (entity,{posit Ion: "Relative"}); var content = entity.innerhtml; entity.innerhtml = ""; !+ "\v1"? This. Iegradient (Entity,stops,width,height,type): this. Svggradient (entity,stops,width,height,type) var contentdiv = document.createelement ("div"); This.css (contentdiv,{Position: "Absolute", top:0,left:0}) contentdiv.innerhtml = content; Entity.appendchild (CONTENTDIV); }, Css:function (node,bag) {var str = ";" for (var i in bag) {if (Bag.hasownproperty (i)) str + = i+ ": +bag[i]+";} Node.style.cssText = str; }, Attr:function (Node,bag) {for (var i in bag) {if (Bag.hasownproperty (i)) Node.setattribute (I,bag[i])}}, CREATESV G:function (tag) {return Document.createelementns ("Http://www.w3.org/2000/svg", tag); }, Setfilter:function (el,start,end,type) {el.style.filter = ' progid:DXImageTransform.Microsoft.Gradient (enabled= ' True ', startcolorstr= "+ start+", gradienttype= "+type+", endcolorstr= "+end+") "; }, Createstop:function (Parent,top,left,width,height,type) {if (type) {var table = document.createelement ("table"); Parent.appendchild (table); var tr = table.insertrow (0), TD = Tr.insertcell (0) this.attr (table,{height:height+ "px", width:width+ "px", cellpadding:0 , cellspacing:0}) this.css (table,{position: "Absolute", top:top+ "px", left:left+ "px"}); td.innerhtml = ""; return TD; var div = document.createelement ("div"); Parent.appendchild (DIV); This.css (div,{height:height+ "px", width:width+ "px"}) return div; }, Iegradient:function (Entity,stops,width,height,type) {var offset,color,beforecolor,stopwidth,stopheight,left, Top,stop; for (Var i=0,j=0,l=stops.length;i<l;i++,j++) {offset = Stops[i].split (",") [0]; color = This.hex (Stops[i].split (",") [1]); Stopwidth = (offset/100 * width). toFixed (1); Stopheight = (offset/100 * height). toFixed (1); switch (i) {case 0:beforecolor = color; left = Stopwidth; top = stopheight; if (offset!= 0) {//Insert a solid-colored table stop = type? This.createstop (Entity,0,0,stopwidth,height,type): This.createstop (Entity , 0,0,width,stopheight,type); This.css (Stop,{background:color}); } break; Case L-1://First insert a gradient table var w2 = (100-offset)/100 * width). toFixed (1), H2 = ((100-offset)/100 * height). toFixed (1), Stop = type? This.createstop (Entity,0,left,width-left-w2,height,type): this.Createstop (Entity,0,0,width,height-top-h2,type); This.setfilter (Stop,beforecolor,color,type); if (offset!= 100) {//Then insert a solid-colored table var stop2 = type? This.createstop (entity,0,stopwidth,w2,height,type): This.createsto P (Entity,0,0,width,h2,type); This.css (Stop2,{background:color}); } break; Default://Insert a gradient of table stop = type? This.createstop (Entity,0,left,stopwidth-left,height,type): This.createstop (Entity,0,0,width,stopheight-top,type ); This.setfilter (Stop,beforecolor,color,type); Beforecolor = color; left = Stopwidth; top = stopheight; Break }}, Svggradient:function (Entity,stops,width,height,type) {var svg = this.createsvg ("SVG"), id = "id" + (new Date () . GetTime () * Math.random ()). toFixed (0); This.attr (svg,{width:width+ "px", height:height+ "px"}) entity.appendchild (SVG); var defs = this.createsvg ("defs"); Svg.appendchild (defs); var lineargradient = this.createsvg ("LinearGradient"); Defs.appendchild (lineargradient); This.attr (lineargradient,{id:id,x1: "0%", y1: "0%"}) if (type) {this.attr (lineargradient,{x2: "100%", y2: "0%"})}else{this.attr (lineargradient,{x2: "0%", Y2: "100%"})} for (Var i=0,j=0,l=stops.length;i<l;i++,j++) {var offset = Stops[i].split (",") [0] + '% ', color = this. Hex (Stops[i].split (",") [1]), stop = This.createsvg ("Stop"); This.attr (Stop,{offset:offset, "Stop-color": color}); Lineargradient.appendchild (stop); var rect = this.createsvg ("rect"); Svg.appendchild (rect); This.attr (rect,{x: "0px", Y: "0px", width:width+ "px", height:height+ "px", fill: "URL (#" +lineargradient.getattribute (" ID ") +") "}); }, Hex:function (value) {if (/^#/.test (value)) {value = Value.replace (' # ', '); Return "#" + (Value.length = 3 Value.replace (/^ (\w) (\w) (\w) $/, ' $1$1$2$2$3$3 '): value); return value; } window.onload = function () {New gradient ("Text1", {width:800,height:100,type:1, "color-stop": ["0,red", "16,orange", "32,yellow", "48,green", "64,blue", "80,indigo", "100,violet"]}) New gradient ("Text2", {width:800,height:100,type:0, "Color-stop": ["0,red", "16,orange", "32,yellow", "48,green", "64,blue", "80,indigo", "100,violet"]} </script > <div id= "Text1" class= "gradient" >javascript linear gradient by Shizhong the United States to achieve multiple horizontal gradient effect </div> <div id= "Text2" class= "G Radient ">javascript linear gradient by Shizhong us to achieve multiple vertical gradients </div>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
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.