先来ie的,这是最大的用户群,如果这部分开发不出来,基本可以说不用做了。ie虽然有gradient滤镜,但对比其他浏览器的实现特弱,没有多重渐变(stop-color),不能实现角度渐变,而且还经常失效。我的思路是这样,假如有一个带文本的div,要实现多重线性渐变,我们首先得把它里面的文本取出来,然后里面放几个div,有几重就放几个,然后把它们渐变。如果是垂直渐变,这好办,什么也不用做,只需设置其滤镜与各个高就行了。如果水平,就让其浮动或绝对定位,放到适当的位置,设置其滤镜与宽。但渐变滤镜竟然会在浮动后或定位后失效,这是在使用透明滤镜时闻所未闻的。没有办法,祭出上古神器table。但设置长与宽时,使用style来设置是不顶用的,一定要用dom属性。渐变则由它的td元素负责。为了去除table元素与td元素之间,td元素与其内容之间的空白,我们还得用到cellpadding与cellspacing。
javascript线性渐变 by 司徒正美javascript线性渐变 by 司徒正美 实现多重水平渐变效果
必须在ie中才能看到效果!
[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;ivar 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;ivar 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中我们也能实现线性渐变了。
下面这个运行框里的渐变效果可在所有主流浏览器中正常运作。
javascript线性渐变 by 司徒正美javascript线性渐变 by 司徒正美 实现多重水平渐变效果
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]})
javascript线性渐变 by 司徒正美javascript线性渐变 by 司徒正美 实现多重水平渐变效果
javascript线性渐变 by 司徒正美 实现多重垂直渐变效果
[ctrl+a 全选 注:如需引入外部js需刷新才能执行]