[英]Html button colour change on click
希望這是一個非常簡單的應用程序,我正在使用 flask 和 python 構建一個 web 應用程序。 在應用程序的前端,我試圖讓它改變按下按鈕的顏色並將之前的任何顏色更改恢復為其他按鈕,因此只有最近選擇的按鈕是不同的顏色。
這些按鈕是從 sql 數據庫中填充的,因此所有按鈕都在 for 循環中使用相同的 html 行。 以下是我目前擁有的代碼:
換色腳本:
<script>
var count = 0;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "red"
count = 0;
}
else {
count = 1;
}
}
按鈕代碼:
{% for item in categorydata %}
<tr>
<button id="{{item[0]}}" formtarget="Items" name="ItemCategory" value={{item[0]}} onClick="setColor('{{item[0]}}', '#101010')" style="color:black;height:50px;width:150px" >{{item[0]}}</button>
</tr>
{% endfor %}
關於如何做到這一點的任何想法?
對於這種問題你不需要使用 JS。 你要做的是使用css:focus psuedo-class
例如:
.btn:focus {
background-color: red;
}
因此,這樣做的一種方法是將 class “修改”添加到按下的按鈕並從先前按下的按鈕中刪除 class “修改”
modified {
background-color: black;
}
function calledOnClick(id){
previousPressedButton = document.getElementsByClassName("modified")[0]; //there should only be one item, check before hand if items exist ofcourse.
previousPressedButton.classList.remove("modified")
pressedButton = document.getElementById(id)
pressedButton.classList.add("modified")
}
<button id=1 onclick="calledOnClick(this.id)"></button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.