[英]make a Toggle button in javascript
我想要一个切换按钮,它的当前css背景颜色值为“红色”。 在第一次点击它应该变为'黄色',在第二次点击它变为'绿色',在第三次点击它应该变回'红色'。
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中的值。 谁能帮我写一个有效的解决方案。
而不是检查当前的颜色, 知道当前的颜色!
var colors = ['red', 'yellow', 'green'];
var currentColor = 0;
然后变化变得美好而直截了当:
$('#box').mousedown(function () {
currentColor++;
var newColor = colors[currentColor % colors.length];
$(this).css('background-color', newColor);
});
一种不那么精细的方法可能是:
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>
应该管用。
您可以使用此代码:(不是非常优雅但功能齐全,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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.