更改所有点击按钮的颜色
我在以下形式的HTML页面中有一组按钮:
<button
id="testID"
mat-mini-fab
ngClass="list-button"
(click)="onClick($event)"
>
Press
</button>
我尝试更改属于.list-button类的每个按钮的颜色,然后使用以下CSS代码单击它:
.list-button:focus {
background-color: #7d698d;
}
但是,当按钮i的颜色i的颜色i单击每次更改 (所有先前单击的按钮的颜色也会更改为原始颜色)。 我该如何解决?我希望所有单击的按钮保持其新颜色。
我还尝试为此类的按钮分配一个ID,并在onClick()方法中更改其颜色,但没有成功。同样的问题仍然存在。你能帮我吗?
onclick(event: any) {
const btn = document.getElementById('testID');
if (btn) btn.style.backgroundColor = '#7d698d';
}
I have a set of buttons in an html page of the following form:
<button
id="testID"
mat-mini-fab
ngClass="list-button"
(click)="onClick($event)"
>
Press
</button>
I try to change the color of each button belonging to .list-button class after clicking on it using the following css code:
.list-button:focus {
background-color: #7d698d;
}
However, while the color of the button I click each time changes
(the color of all the previously clicked buttons also changes back to their original color).
How could I fix it? I want all the clicked buttons to remain their new color.
I also tried assigning an id to the buttons of this class and changing their color inside the onClick() method as follows without success. The same problem remains. Could you help me, please?
onclick(event: any) {
const btn = document.getElementById('testID');
if (btn) btn.style.backgroundColor = '#7d698d';
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
el
,它将this
作为参数函数
函数onclick(el){.............. 并使用它onclick(this)
id
您可以直接使用el.style
或event .target.Style
请参阅下一个示例另外您可以使用该功能并通过
event
等于event
作为参数函数
onclick(event)函数onclick(event){..... 。}
并使用el
which will refer tothis
as an argumentfunction onClick(el){......}
and use itonClick(this)
id
you can directly useel.style
orevent.target.style
see the next examplesAlso You can use the function and pass
event
which equalevent
as an argumentfunction onClick(event){......}
and use itonClick(event)
您需要获取发射事件的按钮的ID
You need to get the id of the button that fired the event
单击另一个按钮后,先前单击按钮的颜色重置的颜色是将焦点设置在最后一个单击按钮上的原因。尝试在Venkatesh答案中使用代码。
The reason why the color of the previously clicked buttons is resetting after you click on another one is that the focus is set on the last clicked button. Try using the code in the Venkatesh's answer.
无需JS。在样式表中使用
focus
选择器。〜 w3
用JS编辑〜。此方法使用
.querySelectorAll(“ button”)
并每次单击按钮(s)时切换样式的类.focus
。有多个按钮时,这很好。No need for js. Use the
focus
selector in your stylesheet.~ W3
Edit ~ with js. This method uses
.querySelectorAll("button")
and toggles the styled class.focus
each time the button(s) are clicked. This works well when having multiple buttons.