悬停时的jQuery函数

时间:2014-08-13 21:13:27

标签: javascript jquery

我想创建一个在我悬停元素时触发的自定义函数。 通常的(我认为)解决方案就是选择元素和.hover(函数) 我想创建一个如下所示的函数:

name(element,inColor,outColor,time)
{
    element.hover(animate{color:inColor,duration:time},{animate:outColor,duration:time})
}

并在我想要动画的每个元素上调用此函数。问题是我必须把它固定在一个事件上,不能只说

name($("a"),"#000","#fff",250);

我无法弄清楚如何在悬停时触发功能。 这是否可能,因为它是一个双线,它是否值得一个功能?

2 个答案:

答案 0 :(得分:4)

这里的问题在于您的语法。

.hover()接受两个函数分别完成onmouseenteronmouseleave

让我们来看看你的功能:

element.hover(animate{color:inColor,duration:time},{animate:outColor,duration:time})

animate{...}不是调用.animate()函数的正确方法。另外,duration应该在对象之外,因为它不是CSS属性(你混合了调用animate()的两种不同方式:我假设你想要.animate(plainObject properties, duration time),但如果你想要另一个,请查看我链接到的文档。看起来应该更像这样:

element.hover(function(){ $(this).animate({color:inColor,}, time); }, ... );

现在是第二部分:{animate:outColor, duration:time}。这根本不起作用。您正在寻找的是:

function(){ $(this).animate({color:outColor}, time); }

合:

element.hover(function(){ $(this).animate({color:inColor,}, time); }, function(){ $(this).animate({color:outColor,}, time); });

如果你想要一个格式好/可读的版本:

function name(element, inColor, outColor, time) {
    element.hover(function () {
        $(this).animate({
            color: inColor,
        }, time);
    }, function () {
        $(this).animate({
            color: outColor,
        }, time);
    });
}

Demo

答案 1 :(得分:0)

也许这会对你有所帮助:

function name(element,inColor,outColor,time) {
    element.hover(function(){
        $(this).animate({color:inColor}, time)
    },function(){
        $(this).animate({color:outColor}, time)
    });
}

name($("a"), "#000", "#fff", 250);