如何在jQuery更改背景颜色后重置其背景颜色?

3

首先,在这个JSFiddle链接中,有一个名为“Rockets”的类。该类包含两个方法:一个是更新火箭位置的方法,另一个是初始化火箭的方法。

//  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”类的链接具有背景颜色)。

额外加分项:

如果不同的背景颜色不连续使用两次就加分(例如,如果单击一次将其设置为黄色,则单击两次除了黄色以外的任何其他颜色).

3个回答

4
这将满足您的所有要求(包括奖金)。
$(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);
  });
});

3

只需写下以下内容:

$(this).css({'background-color':''});

1
我点赞了,因为这是标题的完美答案。这正是我在mouseenter事件中更改颜色后需要的mouseleave事件。 - edj

1
只需使用jQuery的.css()方法来删除背景颜色:
$(this).addClass('selected')
    .parent('li').siblings().find('.selected')
    .removeClass('selected').css('background-color', '');

@pimvdb:.siblings() 不会包括 this。所以我们最终会发现 this 有一个 selected 类,而其他链接(li a)没有。 - Joseph Silber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接