我在以下形式的 html 頁面中有一組按鈕:
<button
id="testID"
mat-mini-fab
ngClass="list-button"
(click)="onClick($event)"
>
Press
</button>
在使用以下css代碼單擊它后,我嘗試更改屬于 .list-button 類的每個按鈕的顏色:
.list-button:focus {
background-color: #7d698d;
}
但是,雖然我每次單擊的按鈕顏色都會發生變化(所有先前單擊的按鈕的顏色也會變回其原始顏色)。我該如何解決?我希望所有點擊的按鈕都保持新顏色。
我還嘗試為此類的按鈕分配一個 ID,并在 onClick() 方法中更改它們的顏色,如下所示,但沒有成功。同樣的問題仍然存在。請問你能幫幫我嗎?
onclick(event: any) {
const btn = document.getElementById('testID');
if (btn) btn.style.backgroundColor = '#7d698d';
}
uj5u.com熱心網友回復:
- ID 必須是唯一的
- 您可以使用
el將this作為引數 參考的函式并傳遞function onClick(el){......}并使用它onClick(this) - 無需獲取
id即可直接使用el.style或event.target.style查看下一個示例
function onClick(el){
el.style.backgroundColor = '#7d698d';
}
<button
id="testID-1"
mat-mini-fab
ngClass="list-button"
onclick="onClick(this)"
>
Press
</button>
<button
id="testID-2"
mat-mini-fab
ngClass="list-button"
onclick="onClick(this)"
>
Press
</button>
您也可以使用該函式并將event其event作為引數 傳遞function onClick(event){......}并使用它onClick(event)
function onClick(event){
event.target.style.backgroundColor = '#7d698d';
}
<button
id="testID-1"
mat-mini-fab
ngClass="list-button"
onclick="onClick(event)"
>
Press
</button>
<button
id="testID-2"
mat-mini-fab
ngClass="list-button"
onclick="onClick(event)"
>
Press
</button>
uj5u.com熱心網友回復:
您需要獲取觸發事件的按鈕的 id
onclick(event: any) {
const btn = document.getElementById(event.target.id);
if (btn) btn.style.backgroundColor = '#7d698d';
}
uj5u.com熱心網友回復:
單擊另一個按鈕后,先前單擊的按鈕的顏色會重置的原因是焦點設定在最后單擊的按鈕上。嘗試使用 Venkatesh 答案中的代碼。
uj5u.com熱心網友回復:
不需要js。focus在樣式表中使用選擇器。
:focus在接受鍵盤事件或其他用戶輸入的元素上允許使用選擇器。
~ W3
button.list-button:focus {
background-color: #7d698d;
color: white;
}
<button class="list-button">Click</button>
用js編輯~。每次單擊按鈕時,此方法都會使用.querySelectorAll("button")并切換樣式類。.focus這在有多個按鈕時效果很好。
顯示代碼片段
// Get all the elements on the basis of query selector (button)
let btn = document.querySelectorAll("button");
for (var i = 0; i < btn.length; i ) {
(function(index) {
btn[index].addEventListener("click", function() {
console.log("Clicked Button: " index);
let isPresent = false;
// Checks if the class is present or not
this.classList.forEach(function(e, i) {
if (e == "focus") {
isPresent = true;
} else {
isPresent = false;
}
});
// Toggles the presence of class (.focus) on the basis of the isPresent variable
if (isPresent) {
this.classList.remove("focus");
} else {
this.classList.add("focus");
}
});
})(i);
}
.focus {
background-color: #7d698d;
color: white;
cursor: pointer;
}
<button id="btn">Click</button>
<button id="btn">Click</button>
<button id="btn">Click</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/462525.html
標籤:javascript html css 按钮 点击
上一篇:禁用注冊按鈕Redmine
