我有一个html按钮,当用户点击按钮时,它会将颜色从蓝色变为红色并返回。在jQuery中有更好的方法吗?
clicked = true;
$(document).ready(function() {
$("button").click(function() {
if (clicked) {
$(this).css('background-color', 'red');
clicked = false;
} else {
$(this).css('background-color', 'blue');
clicked = true;
}
});
});

button {
background-color: blue;
height: 100px;
width: 150px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Press</button>
&#13;
答案 0 :(得分:0)
一种方法是为红色背景颜色添加一个类并切换该类:
$("button").click(function(){
$(this).toggleClass("redButton");
});
button{
background-color: blue;
height:100px;
width:150px;
}
.redButton { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Press</button>
答案 1 :(得分:0)
使用jquery和toggleClass:
$("button").click(function(){
$('.btn').toggleClass('toggled');
})
&#13;
.btn{
background-color: blue;
padding: 10px;
color: white;
}
.toggled{
background-color: red;
}
&#13;
<button type="button" class="btn">Press</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
&#13;
答案 2 :(得分:0)
您可以像这样使用切换类功能
clicked = true;
$(document).ready(function(){
$("button").click(function(){
$(this).toggleClass('red');
$(this).toggleClass('blue');
});
});
&#13;
button{
height:100px;
width:150px;
}
.red
{
background-color:red;
}
.blue
{
background-color:blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Button Fun</title>
<script src = 'bower_components/jquery/dist/jquery.js'></script>
<script type="home.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>
<body>
<button class="blue">Press</button>
</body>
</html>
&#13;