[英]jQuery switch from CSS value of div
這個jQuery適用於3個div - leftKey,rightKey和mentors。 它們都正確對齊。 目標是當點擊leftKey時,指導者將循環顯示背景顏色列表。 我定義了數組中的顏色; 紅色然后藍色然后綠色。 我已經獲得了響應點擊的鍵,但是開關不起作用。
$(document).ready(function() {
var colors = [ "rgb(128, 0, 0)", "rgb(255, 0, 0)", "rgb(0, 0, 255)", "rgb(0, 128, 0)"];
//burgundy, red, blue, green
var mentors = $("#mentors");
$("#leftKey").click(function() {
if(mentors.css("background-color") == colors[0]) {
mentors.css("background-color", colors[colors.length-1]);
} else {
for(var x = 0; x < colors.length; x++) {
if( mentors.css("background-color") == colors[x]) {
mentors.css("background-color", colors[x-1]);
}
}
};
});
$("#rightKey").click(function() {
if( mentors.css("background-color") == colors[colors.length-1]){
mentors.css("background-color", colors[0]);
} else {
for(var x = 0; x < colors.length; x++) {
if( mentors.css("background-color") == colors[x] ) {
mentors.css("background-color", colors[x+1]);
return false;
}
}
};
});
為了簡化你的生活,需要進行一些重構。 嘗試這個:
var colors = [ "red", "blue","green"],
getColor = function (leftRight, currentColor) {
var newColorIndex
isLeft = leftRight === "left";
if (currentColor === colors[0]) {
newColorIndex = (isLeft) ? 2 : 1;
} else if (currentColor === colors[1]) {
newColorIndex = (isLeft) ? 0 : 2;
} else {
newColorIndex = (isLeft) ? 1 : 0;
}
return colors[newColorIndex];
},
colorSwitch = function (leftRight) {
var mentors = $("#mentors"),
currentColor = mentors.css("background-color"),
newColor = getColor(leftRight, currentColor);
$("#mentors").css("background-color", newColor);
};
$(document).ready(function() {
$("#leftKey").click(function() {
colorSwitch("left");
});
$("#rightKey").click(function() {
colorSwitch("right");
});
});
你不能那樣做因為$("#mentors").css("background-color");
返回rgb中的顏色,例如 rgb(255, 0, 0)
您可以通過遞增和遞減索引來實現它。 這樣做的好處是,您可以在colors
數組中擁有任意數量的colors
而無需在switch語句中添加另一個案例:
$(document).ready(function() {
var index = 0;
var colors = [ "red", "blue", "green" ];
$("#mentors").css("background-color", colors[index]);
$("#leftKey").click(function() {
index -= 1;
if (index < 0)
index = colors.length - 1;
$("#mentors").css("background-color", colors[index]);
});
$("#rightKey").click(function() {
index += 1;
if (index >= colors.length)
index = 0;
$("#mentors").css("background-color", colors[index]);
});
});
演示: http : //jsfiddle.net/w3h46/4/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.