jQuery函数问题

时间:2012-02-23 06:14:42

标签: jquery jquery-animate

我的简单jQ功能看起来像

$.fn.animateHighlight = function(highlightColor,type, duration) {
    var highlightBg = highlightColor || "#FFFF9C";
    var animateMs = 1500;
    this.stop().css(type, highlightBg).delay(duration).animate({
        type: "black"
    }, animateMs);
};

这样打电话

$("#qparamstitle").animateHighlight("red","color", 3000);
$("#params").animateHighlight("red","border-color", 3000);

尝试制作类型 - 变量。一切都很好,除了动画。我做错了什么,以及如何让它发挥作用?

2 个答案:

答案 0 :(得分:1)

{
   type: "black"
}

这是使用"type"键创建一个对象。您不能将变量用作对象文字中的键。

您需要先声明变量,然后使用[]设置值。

$.fn.animateHighlight = function(highlightColor,type, duration) {
    var highlightBg = highlightColor || "#FFFF9C";
    var animateMs = 1500;
    var animateVal = {}; // declare object
    animateVal[type] = 'black'; // set `type` value
    this.stop().css(type, highlightBg).delay(duration).animate(animateVal, animateMs);
};

答案 1 :(得分:0)

您需要 jQuery UI 才能 animate colors ,jQuery只支持它。

此外,将选项对象传递给animate函数的方式不起作用。您必须在函数外部创建一个对象并传递对象:

$.fn.animateHighlight = function(highlightColor,type, duration) {
    var highlightBg = highlightColor || "#FFFF9C";
    var animateMs = 1500;
    // create objects for the animation options
    var o = {};
    // using the array notation
    // you can create a property of name "type"
    o[type] = 'Black';
    this.stop().css(type, highlightBg).delay(duration).animate(o, animateMs);
};

<强> DEMO