如何在jQuery更改后重置背景颜色? [英] How to reset background colour after it is changed by jQuery?

查看:115
本文介绍了如何在jQuery更改后重置背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,jsfiddle ...
http://jsfiddle.net/therocketforever/ jYba3 / 11 /

First, a 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]);

现在提问,

首先,此代码的工作方式几乎与我希望的方式相同,用户单击链接,所选颜色应用于链接文本,从其他文本中删除&链接的背景设置为随机来自颜色阵列的颜色。很酷。

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.

我想知道的是......我怎么做才能让随机设置的背景颜色从非选定链接(即。只有.selected类的链接具有背景颜色。)

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.)

EXTRA CREDIT

EXTRA CREDIT

如果连续两次使用相同的背景颜色,则为Bonas积分。 (即如果单击一个设置为黄色,则单击两个除了黄色之外的任何其他颜色。

Bonas points if the same background colour is never used twice in a row. (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);
  });
});

这篇关于如何在jQuery更改后重置背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆