javascript 線性漸層二_javascript技巧

來源:互聯網
上載者:User
先來IE的,這是最大的使用者群,如果這部分開發不出來,基本可以說不用做了。IE雖然有Gradient濾鏡,但對比其他瀏覽器的實現特弱,沒有多重漸層(stop-color),不能實現角度漸層,而且還經常失效。我的思路是這樣,假如有一個帶文本的DIV,要實現多重線性漸層,我們首先得把它裡面的文本取出來,然后里面放幾個DIV,有幾重就放幾個,然後把它們漸層。如果是垂直漸層,這好辦,什麼也不用做,只需設定其濾鏡與各個高就行了。如果水平,就讓其浮動或絕對位置,放到適當的位置,設定其濾鏡與寬。但漸層濾鏡竟然會在浮動後或定位後失效,這是在使用透明濾鏡時聞所未聞的。沒有辦法,祭出上古神器table。但設定長與寬時,使用style來設定是不頂用的,一定要用DOM屬性。漸層則由它的td元素負責。為了去除table元素與td元素之間,td元素與其內容之間的空白,我們還得用到cellPadding與cellSpacing。
<!doctype html> <title>javascript線性漸層 by 司徒正美</title> <meta charset="utf-8"/> <meta name="keywords" content="javascript線性漸層 by 司徒正美" /> <meta name="description" content="javascript線性漸層 by 司徒正美" /> <style type="text/css"> #gradient{ width:800px; height:200px; border:1px solid red; } </style> <script type="text/javascript"> //④使用IE濾鏡實現漸層 function setFilter(el,start,end,type){ el.style.filter = "progid:DXImageTransform.Microsoft.Gradient(enabled='true',startColorstr="+start+",GradientType="+type+", endColorstr="+end+")"; } //③每個漸層體的實現,是用table還是div function createStop(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) 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; } //②漸層的具體實現,確定要使用多少漸層體,每個漸層體的顏色(是漸層色還是純色)與長寬座標 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){ //插入一個純色的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: //先插入一個漸層的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){ //再插入一個純色的table var stop2 = type? createStop(entity,0,stopWidth,w2,height,type): createStop(entity,0,0,width,h2,type); stop2.style.backgroundColor = color; } break; default : //插入一個漸層的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; } } } //①漸層的主體函數 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 = ""; //向目標對象進行漸層。 IEgradient(entity,stops,width,height,type); //把原來的內容重新加入的目標對象。 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線性漸層 by 司徒正美 實現多重水平漸層效果</div> <p">必須在IE中才能看到效果!</p>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]

safari,chrome與opera打算都用SVG實現。為了減少函數的長度,特意搞了兩個輔助函數。
複製代碼 代碼如下:

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則利用其私人屬性:
複製代碼 代碼如下:

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;"
}

不過今天研磨一下,發現firefox還是支援SVG的線性漸層的,因此糾正我原來的觀點。上面的函數只是作用一種實現手段放在這裡,它並沒有整合到我最終的版本中(雖然它比SVG實現短很多。)這樣一來,在老一點版本的firefox中我們也能實現線性漸層了。
下面這個運行框裡的漸層效果可在所有主流瀏覽器中正常運作。
<!doctype html> <title>javascript線性漸層 by 司徒正美</title> <meta charset="utf-8"/> <meta name="keywords" content="javascript線性漸層 by 司徒正美" /> <meta name="description" content="javascript線性漸層 by 司徒正美" /> <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.hasOwnProperty(i)) node.setAttribute(i,bag[i]) } }; //④使用IE濾鏡實現漸層 function setFilter(el,start,end,type){ el.style.filter = "progid:DXImageTransform.Microsoft.Gradient(enabled='true',startColorstr="+start+",GradientType="+type+", endColorstr="+end+")"; } //③每個漸層體的實現,是用table還是div function createStop(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) 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)"}); } //②漸層的具體實現,確定要使用多少漸層體,每個漸層體的顏色(是漸層色還是純色)與長寬座標 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){ //插入一個純色的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: //先插入一個漸層的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){ //再插入一個純色的table var stop2 = type? createStop(entity,0,stopWidth,w2,height,type): createStop(entity,0,0,width,h2,type); css(stop2,{background:color}); } break; default : //插入一個漸層的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; } } } //①漸層的主體函數 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線性漸層 by 司徒正美 實現多重水平漸層效果</div> https://developer.mozilla.org/en/SVG/Tutorial/Fill_Stroke_and_Gradients
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]

再把它做成類。扼要說明一下:它的第一個參數為IE,第二個為雜湊。雜湊中的各參數都為必選的,width,height的單位為px;type為0或者1,0代表垂直,1為水平;color-stop代表漸層體,由一個字串數組構成,每個字串都是由數字加逗號加顏色值組成,數字表代位移量,單位為%,顏色值可以是red,green等名詞,也可以是六位或三位的雜湊值。漸層體至少要有一個。
複製代碼 代碼如下:

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線性漸層 by 司徒正美</title> <meta charset="utf-8"/> <meta name="keywords" content="javascript線性漸層 by 司徒正美" /> <meta name="description" content="javascript線性漸層 by 司徒正美" /> <style type="text/css"> .gradient{ width:800px; height:100px; } </style> <script type="text/javascript"> 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"]; this.init(entity,stops,width,height,type); } Gradient.prototype ={ constructor: Gradient, init: function(entity,stops,width,height,type) { this.css(entity,{position:"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]) } }, createSVG: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){ //插入一個純色的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: //先插入一個漸層的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){ //再插入一個純色的table var stop2 = type? this.createStop(entity,0,stopWidth,w2,height,type): this.createStop(entity,0,0,width,h2,type); this.css(stop2,{background:color}); } break; default : //插入一個漸層的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線性漸層 by 司徒正美 實現多重水平漸層效果</div> <div id="text2" class="gradient">javascript線性漸層 by 司徒正美 實現多重垂直漸層效果</div>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.