[英]How to reset background colour after it is changed by jQuery?
首先,一個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類的鏈接才具有背景色。)
額外信用
Bonas指出是否從未連續兩次使用相同的背景色。 (即,如果單擊一個設置為黃色,則單擊兩個是除黃色以外的任何其他顏色。
這將滿足您的所有要求(包括獎金)。
$(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':''});
只需使用jQuery的.css()
方法即可刪除背景色:
$(this).addClass('selected')
.parent('li').siblings().find('.selected')
.removeClass('selected').css('background-color', '');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.