这里的回调功能不起作用。我认为我错误地使用了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次更好。

有帮助吗?

解决方案

在两个功能之外声明它,然后删除 " + + "

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)是为了使 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...

...再次知道我认为它可能在最新版本中被打破,您需要进行测试,因为有时可能会变得薄弱。

其他提示

" + + " 没有道理。只是使用

$(this).stop().animate({ color: startColor}, 350);  //Start color  });  

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

相反,您应该使用旧颜色使用 $.data.
另外,请勿在变量周围放语;这使其成为一个字符串。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top