【发布时间】:2021-10-18 15:25:54
【问题描述】:
我需要将.important-element 更改为与按下同名按钮相同的颜色。我想通过将.red、.blue、.green 类名添加到.important-element 来实现这一点,如果按下了另一个或相同的按钮,也将它们删除。我不确定如何编辑我的 jQuery 代码以使其正常工作。
重要的事情:按下按钮后,它需要删除以前添加的类名(就像 jQuery 代码现在可以使用按钮一样)。换句话说:如果一个按钮已经处于活动状态,它需要在按下另一个按钮时从.important-element 中删除它添加的类名。
$('.btn').on("click", function() {
$('button').not(this).removeClass('active');
$(this).toggleClass('active');
})
.price-filter-container {width: 1190px;max-width:100%;
margin: 0 auto;}
button {outline: 0; /* only to remove the ugly blue outline in this demo */}
button.active {color: white;}
button.green.active {background:green;}
button.red.active {background:red;}
button.blue.active {background:blue;}
.important-element {padding:20px; width:240px; text-align:center; background:grey; margin-top:30px; color:#FFF;}
.important-element.green {background:green}
.important-element.red {background:red}
.important-element.blue {background:blue}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price-filter-container">
<button class="btn green">green</button>
<button class="btn red">red</button>
<button class="btn blue">blue</button>
</div>
<div class="important-element">i need to change with button click to the same collor as the button</div>
【问题讨论】: