|
[Ctrl+A 全選 注:如需引入外部Js需刷新才能執(zhí)行]
safari,chrome與opera打算都用SVG實(shí)現(xiàn)。為了減少函數(shù)的長(zhǎng)度,特意搞了兩個(gè)輔助函數(shù)。
復(fù)制代碼 代碼如下:
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則利用其私有屬性:
復(fù)制代碼 代碼如下:
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;"
}
不過(guò)今天研磨一下,發(fā)現(xiàn)firefox還是支持SVG的線性漸變的,因此糾正我原來(lái)的觀點(diǎn)。上面的函數(shù)只是作用一種實(shí)現(xiàn)手段放在這里,它并沒(méi)有整合到我最終的版本中(雖然它比SVG實(shí)現(xiàn)短很多。)這樣一來(lái),在老一點(diǎn)版本的firefox中我們也能實(shí)現(xiàn)線性漸變了。
下面這個(gè)運(yùn)行框里的漸變效果可在所有主流瀏覽器中正常運(yùn)作。
[Ctrl+A 全選 注:如需引入外部Js需刷新才能執(zhí)行]
再把它做成類(lèi)。扼要說(shuō)明一下:它的第一個(gè)參數(shù)為IE,第二個(gè)為哈希。哈希中的各參數(shù)都為必選的,width,height的單位為px;type為0或者1,0代表垂直,1為水平;color-stop代表漸變體,由一個(gè)字符串?dāng)?shù)組構(gòu)成,每個(gè)字符串都是由數(shù)字加逗號(hào)加顏色值組成,數(shù)字表代偏移量,單位為%,顏色值可以是red,green等名詞,也可以是六位或三位的哈希值。漸變體至少要有一個(gè)。
復(fù)制代碼 代碼如下:
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"]})
[Ctrl+A 全選 注:如需引入外部Js需刷新才能執(zhí)行]
JavaScript技術(shù):javascript 線性漸變二,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。