【问题标题】:How to reset background colour after it is changed by jQuery?jQuery更改背景颜色后如何重置背景颜色?
【发布时间】:2011-11-11 13:27:37
【问题描述】:

首先,一个 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 类的链接具有背景颜色。)

额外信用

如果相同的背景颜色从未连续使用两次,则奖励积分。 (即如果点击一设置为黄色,点击二为除黄色以外的任何其他颜色。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    这将满足您的所有要求(包括奖金)。

    $(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);
      });
    });
    

    【讨论】:

      【解决方案2】:

      就这样写吧:

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

      【讨论】:

      • 我投了赞成票,因为这是标题的完美答案。这是我在 mouseenter 中更改颜色后在 mouseleave 事件中所需要的。
      【解决方案3】:

      只需使用jQuery的.css()方法去除背景色:

      $(this).addClass('selected')
          .parent('li').siblings().find('.selected')
          .removeClass('selected').css('background-color', '');
      

      【讨论】:

      • @pimvdb: .siblings() 将不包括 this。所以我们最终会得到 this 有一个 selected 类,而其他链接 (li a) 没有。
      猜你喜欢
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 2011-05-16
      相关资源
      最近更新 更多