我的页面中有很多连续的按钮。当我点击按钮时,我需要更改按钮颜色。这是我的示例代码
$( "button.change" ).click(function() {
$(this).toggleClass( "selected" );
});
.Button {
font-family: Calibri, sans-serif;
font-size:13px;
font-weight: bold;
width: 160px;
height: 25px;
background:grey;
color: white
}
.selected {
color: white;
background:green
}
button#cssColorChange:active{
color: white;
background:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
这是工作。但是在这里,当我点击每个按钮时,颜色都发生了变化。我需要,当我点击一个 Button 时,应该只更改该 Button 的颜色,而其余 Buttons 颜色应该默认。
最佳答案
是这样的吗?
$( "button.change" ).click(function() {
$( "button.change.selected" ).removeClass("selected");
$(this).toggleClass( "selected" );
});
.Button {
font-family: Calibri, sans-serif;
font-size:13px;
font-weight: bold;
width: 160px;
height: 25px;
background:grey;
color: white
}
.selected {
color: white;
background:green
}
button#cssColorChange:active{
color: white;
background:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
<br><br>
<button class="Button change" id="jQueryColorChange">Click to change color</button>
关于javascript - 单击按钮时更改按钮颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44199397/