用jQuery动画渐变



这将是我今天的问题列表。是否有可能在jQuery中动画径向梯度(使用.animate),如果是,如何?

background: -webkit-gradient(
    radial, 50% 50% ,0, 50% 50%, 70, from(rgb(25,25,25)), to(rgb(50,50,50))
);

你不能在jQuery中默认这样做,你甚至不能在没有相应插件的情况下动画平面颜色

动画渐变是困难的,因为浏览器之间的语法差异。我为一个非常具体的情况写了一个插件,可能对你有用。这是一个线性渐变,但你可以调整它为径向。

jQuery.fx.step.gradient = function(fx) {
    if (fx.state == 0) { //On the start iteration, convert the colors to arrays for calculation.
        fx.start = fx.elem.style.background.match(/d+/g); //Parse original state for numbers.  Tougher because radial gradients have more of them
        fx.start[0] = parseInt(fx.start[0]);
        fx.start[1] = parseInt(fx.start[1]);
        fx.start[2] = parseInt(fx.start[2]);
        fx.end = fx.end.match(/d+/g);
        fx.end[0] = parseInt(fx.end[0]);
        fx.end[1] = parseInt(fx.end[1]);
        fx.end[2] = parseInt(fx.end[2]);
    }
    fx.elem.style.background = "-webkit-linear-gradient(rgb(" + [
        Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
        Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
        Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
        ].join(",") + ")," + "rgb(0,0,0))";
}
$(this).animate({"gradient": "rgb(0, 255, 0)"});

演示。

您可能想要创建两个函数,一个用于内部颜色(jQuery.fx.step.innerColor),另一个用于外部颜色(jQuery.fx.step.outerColor),将像这样调用:

$(this).animate({"innerColor": "rgb(25,25,25)",
                 "outerColor": "rgb(50,50,50)"});

最新更新