1

这里的回调函数不起作用。我想我错误地使用了 startColor 变量。

注意:这需要 jQuery UI。

$("a").hover(function() { 
    var startColor = $(this).css("color");
    $(this).stop().animate({ color: "#54a888"}, 350);
    },function() {  
    $(this).stop().animate({ color: " + startColor + "}, 350);
});

多谢你们。我实际上是在尝试重构这段代码:

$("nav ul li a, aside ul li a").hover(function() {  
    $(this).stop().animate({ color: "#54a888"}, 350);  //End color
    },function() {  
    $(this).stop().animate({ color: "#5944b2"}, 350);  //Start color
});
$("h5#logo a, button").hover(function() {  
    $(this).stop().animate({ backgroundColor: "#54a888"}, 350);
    },function() {  
    $(this).stop().animate({ backgroundColor: "#000000"}, 350);
});
    $("h3 a").hover(function() {  
    $(this).stop().animate({ color: "#54a888"}, 350);
    },function() {  
    $(this).stop().animate({ color: "#000000"}, 350);
});

我有不同的起始颜色和不同的属性要设置动画。似乎有比重复相同代码 3 次更好的解决方案。

4

3 回答 3

1

" + + "没有意义。只需使用

$(this).stop().animate({ color: startColor}, 350);  //Start color  });  
于 2011-01-13T21:26:44.703 回答
1

在两个函数之外声明它,并删除" + + "

var startColor;

$("a").hover(function() { 
    startColor = $(this).css("color");
    $(this).stop().animate({ color: "#54a888"}, 350);  //End color
},function() {  
    $(this).stop().animate({ color: startColor}, 350);  //Start color  
}); 

...或者更好的是,用于.data()记住该特定元素的颜色:

$("a").hover(function() { 
    if( !$(this).data( 'startColor' ) ) {
        $(this).data( 'startColor', $(this).css("color") );
    }
    $(this).stop().animate({ color: "#54a888"}, 350);  //End color
},function() {  
    $(this).stop().animate({ color: $(this).data('startColor')}, 350);  
}); 

...或者如果所有链接的颜色恰好相同,则只需获取一次,然后重用该值。它实际上可能更安全,因为您正在处理动画。

var startColor = $(a).css("color");

$("a").hover(function() { 
    $(this).stop().animate({ color: "#54a888"}, 350);  //End color
},function() {  
    $(this).stop().animate({ color: startColor}, 350);  //Start color  
}); 

编辑:根据您更新的问题,您似乎正在尝试减少代码。似乎它们之间存在足够的差异,以至于尝试合并会很复杂,以至于您最终可能会得到更多代码。

减少的一种方法是将您的hover()处理程序更改为接受 1 个函数而不是 2 个:

$("h3 a").hover(function( e ) {  
    $(this).stop().animate({ color: e.type == 'mouseenter' ? "#54a888" : "#000000"}, 350);
});

缩短一点。

另一种选择(因为我假设您使用的是 jQueryUI)是为 a 设置动画toggleClass(尽管我认为它可能在最新版本的 UI 中被破坏)。

$("h3 a,nav ul li a, aside ul li a,nav ul li a, aside ul li a").hover(function( e ) {  
    $(this).stop().toggleClass('hover', 350);
});

然后在 CSS 中:

h3 a.hover {
    color:#000000;
}

nav ul li a.hover, aside ul li a.hover {
    color:#54a888;
}

// etc...

...请再次注意,我认为它可能在最新版本中被破坏,您需要进行测试,因为它有时可能会很脆弱。

于 2011-01-13T21:27:04.743 回答
0

您正在一个回调中创建一个局部变量,并尝试在另一个回调中使用它。

相反,您应该使用$.data.
另外,不要在变量周围加上引号;这使它成为一个字符串。

于 2011-01-13T21:27:18.243 回答