简体   繁体   English

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

[英]How to reset background colour after it is changed by jQuery?

First, a jsfiddle... http://jsfiddle.net/therocketforever/jYba3/11/ 首先,一个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]);

Now a Question, 现在是一个问题

Firstly this code works almost exactly the way that I would like it to, A user clicks a link, the selected colour is applied to the link text, removed from the others & the background of the link is set to a random color from the array of colours. 首先,此代码几乎完全按照我想要的方式工作,用户单击链接,将所选颜色应用于链接文本,从其他文本中删除,并将链接的背景设置为数组中的随机颜色颜色。 Cool. 凉。

What I would like to know is... How would I make it so that the randomly set background colour is removed from the non selected links (ie. Only the link with the .selected class has the background colour.) 我想知道的是...我将如何做,以便从未选中的链接中删除随机设置的背景色(即,只有具有.selected类的链接才具有背景色。)

EXTRA CREDIT 额外信用

Bonas points if the same background colour is never used twice in a row. Bonas指出是否从未连续两次使用相同的背景色。 (ie. If click one sets to yellow, click two is any other colour except yellow. (即,如果单击一个设置为黄色,则单击两个是除黄色以外的任何其他颜色。

This'll meet all your requirements (bonus included). 这将满足您的所有要求(包括奖金)。

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

只需这样写:

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

Just use jQuery's .css() method to remove the background color: 只需使用jQuery的.css()方法即可删除背景色:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM