点击按钮 背景变红 再点击按钮 背景变回原样
首先,对该按钮添加 id ,添加 事件,根据当前样式设置为另一种样式:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.grayClass{background-color: gray}
.redClass{background-color: red}
</style>
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>
function changeBackground(){
var curClass = $("#setBackground").attr("class");
if(curClass == 'grayClass'){
$("#setBackground").attr("class",'redClass');
}else{
$("#setBackground").attr("class",'grayClass');
}
}
</script>
</head>
<body>
<button onclick="changeBackground();" id="setBackground" class="grayClass">设置背景</button>
</body>
</html>
在 http://www.w3school.com.cn/tiy/t.asp?f=jquery_hide 可以查看代码效果。
点击事件判断有没有对应class,有就移除,没有就添加就完了removeClass addClass