2016-04-06 140 views
2

我想要一个具有当前css背景颜色值的切换按钮作为“红色”。 第一次点击它应该变成'黄色', 第二次点击它变成'绿色',而第三次它应该变回'红色'。在javascript中创建切换按钮

HTML

<div id="box" class="boxa"> 1 </div>

的Javascript:

$('div[id="box"]').mousedown(function(){ 


if($(this).css ('background-color', 'red')) { 
     $(this).css ('background-color', 'yellow');  
} 

}); 

但这不起作用为$(this).css ('background-color', 'red')总是返回true, 然后试图存放在变量,然后将值像这样检查

var color = $(this).css ('background-color'); 
if (color=="red") { 
    // change it to some other color 
} 

但是这不起作用color返回RGB值。 任何人都可以帮我写一个工作解决方案。

回答

10

而不是检查当前颜色,知道目前的颜色!

var colors = ['red', 'yellow', 'green']; 
var currentColor = 0; 

随后的变化变得漂亮和直观:

$('#box').mousedown(function() { 
    currentColor++; 
    var newColor = colors[currentColor % colors.length]; 

    $(this).css('background-color', newColor); 
}); 
+0

能否请您解释一下'颜色[currentColor%的色彩。长度]'? –

+0

@RameshPareek:'currentColor%colors.length'是'currentColor'除以'colors.length'的余数。由于'currentColor'增加0,1,2,3,4,5,6,...,'currentColor%colors.length'为0,1,2,0,1,2,0,...。换句话说,它会在到达结尾后回到数组​​的开始位置。 – Ryan

+0

有趣的逻辑! –

0

一个少阐述的做法可能是:

JS(jQuery的):

$(".toggledRed").click(function() { 
    $(this).toggleClass("toggledYellow"); 
}); 


$(".toggledYellow").click(function() { 
    $(this).toggleClass("toggledGreen"); 
}); 


$(".toggledGreen").click(function() { 
    $(this).toggleClass("toggledRed"); 
}); 

CSS:

.toggledRed{ 
    background-color:#FF0000; 
} 

.toggledYellow{ 
    background-color:#FFFF00; 
} 

.toggledBlue{ 
    background-color:#0000FF; 
} 

,开始你的HTML有:

<div id="box" class="toggledRed"> 1 </div> 

应该工作。

+0

这将与一个小的改变:事件代表团合作。 '('#box')。parent()。on('click','.toggledRed',...);'。否则'$('。toggledYellow')'和'$('。toggledGreen')'不会选择任何内容,也不会添加事件侦听器。 – Ryan

0

您可以使用此代码:(不是很优雅,但功能,LOL)

$(document).ready(function() { 
 
    $('#b1').click(function() { 
 
    var b = $(this); 
 
    if (b.hasClass("red-class")) { 
 
     b.removeClass("red-class"); 
 
     b.addClass("yellow-class"); 
 
    } else 
 
    if (b.hasClass("yellow-class")) { 
 
     b.removeClass("yellow-class"); 
 
     b.addClass("green-class"); 
 
    } else 
 
    if (b.hasClass("green-class")) { 
 
     b.removeClass("green-class"); 
 
     b.addClass("red-class"); 
 
    } 
 
    }); 
 
});
body { 
 
    padding: 5px; 
 
} 
 
label { 
 
    font-weight: bold; 
 
} 
 
input[type=text] { 
 
    width: 20em 
 
} 
 
p { 
 
    margin: 1em 0 0; 
 
} 
 
.green-class { 
 
    background-color: #2b542c; 
 
} 
 
.red-class { 
 
    background-color: #ff0000; 
 
} 
 
.yellow-class { 
 
    background-color: #ffff00; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> 
 
<label>Change Color in Button</label> 
 
<button id="b1" class="green-class">Hello</button>


JsFiddle link