我想要一个切换按钮,它的当前css背景颜色值为' red'。 在第一次点击它应该改为'黄色', 在第二次点击它变为'绿色',和 第三,它应该改回' red'。
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中的值时,这不起作用。
谁能帮我写一个有效的解决方案。
答案 0 :(得分:10)
而不是检查当前颜色,知道当前颜色!
var colors = ['red', 'yellow', 'green'];
var currentColor = 0;
然后变化变得美好而直截了当:
$('#box').mousedown(function () {
currentColor++;
var newColor = colors[currentColor % colors.length];
$(this).css('background-color', newColor);
});
答案 1 :(得分:0)
不太精心设计的方法可能是:
JS(jQuery):
.toggledRed{
background-color:#FF0000;
}
.toggledYellow{
background-color:#FFFF00;
}
.toggledBlue{
background-color:#0000FF;
}
CSS:
<div id="box" class="toggledRed"> 1 </div>
使用以下命令启动HTML:
{{1}}
应该工作。
答案 2 :(得分: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");
}
});
});
&#13;
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;
}
&#13;
<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>
&#13;