首先,一个 jsfiddle... http://jsfiddle.net/therocketforever/jYba3/11/
// Highlight selected linker link & set all others to default.
$('a.linker').click(function(){
$(this).addClass('selected');
$(this).parent('li').siblings().find('.selected').removeClass('selected');
// Selects a random colour from the 'colors' array by getting a random value
// between 0 and the length of the color array.
rand = Math.floor(Math.random()*colors.length);
$(this).css("background-color", colors[rand]);
现在是一个问题,
首先,这段代码几乎完全按照我希望的方式工作,用户单击一个链接,所选颜色应用于链接文本,从其他颜色中删除,链接的背景设置为随机颜色从颜色的阵列。很酷。
我想知道的是......我将如何做到这一点,以便从非选定链接中删除随机设置的背景颜色(即只有具有 .selected 类的链接具有背景颜色。)
额外学分
如果相同的背景颜色从未连续两次使用,则加分。 (即,如果单击一个设置为黄色,则单击两个设置为黄色以外的任何其他颜色。
最佳答案
这将满足您的所有要求(包括奖金)。
$(document).ready(function(){
// Colours for links
var colors = ["#fff766","#66cef5","#bd7ebc","#66cc66"];
$("a.linker").click(function(){
var $this = $(this).addClass("selected");
$this.parent('li').siblings().find('.selected')
.removeClass('selected').css("background-color", "");
var num = $this.data("colorNum"),
rand = num;
while (num === rand) {
rand = Math.floor(Math.random()*colors.length);
}
$this.css("background-color", colors[rand])
.data("colorNum", rand);
});
});
关于javascript - 如何在 jQuery 更改背景颜色后重置背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7324245/