javascript - 单击按钮时更改按钮颜色

标签 javascript jquery html css

我的页面中有很多连续的按钮。当我点击按钮时,我需要更改按钮颜色。这是我的示例代码

$( "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/

相关文章:

javascript - 在HTML文件中嵌入CSS和JS

javascript - 在这种特殊情况下有什么办法可以避免 ng-repeat 吗?

javascript - 如何使用 javascript 在我的 View 中重复特定的 C# 代码块,甚至应该这样做吗?

html - 文本未垂直对齐

html - 在我的 SharePoint 母版页中显示当前年份

javascript - 为什么 Animated.View 里面的 ScrollView 不起作用?

javascript - 包含数据的 jQuery 空文本区域

javascript - Bootstrap 输入文件游标

javascript - JQuery 模糊事件

java - spring boot无法加载css文件