簡體   English   中英

單擊和確認時更改按鈕的顏色

[英]Changing the color of button on click and confirmation

我有這組角色供用戶(作為按鈕)被選為他們在游戲中的角色。 選擇后,按鈕的顏色應更改為灰色。 但是,單擊按鈕后,顏色會發生變化,但隨后再次變為藍色(在附加的代碼中仍為灰色,但插入原始 HTML 時,它又變回藍色)。 所以目標是 1:點擊后它應該保持灰色,第二件事應該彈出一個確認框來確認“你確定你想要

 .button1 { height:1.5cm; width: 4.5cm; padding: 15px 32px; font-size: 16px; margin: 4px 2px; background-color: #0065bd; color: white; border-radius: 8px; border-color: #E8E8E8; border: none; }.button1:focus { background-color:#585858; border-color: #585858; outline: none; }
 <button class="button1">Brewery 1</button> <button class="button1">Distributor 1</button> <button class="button1">Retailer 1</button> <button class="button1">WholeSaler 1</button> <button class="button1">Brewery 2</button> <button class="button1">Distributor 2</button> <button class="button1">Retailer 2</button> <button class="button1">WholeSaler 2</button> <button class="button1">Brewery 3</button> <button class="button1">Distributor 3</button> <button class="button1">Retailer 3</button> <button class="button1">WholeSaler 3</button>

您的代碼的問題是當按鈕被聚焦時顏色更改完成。 這意味着一旦失去焦點,顏色 go 就會恢復原來的顏色。

您可以做的是在單擊按鈕時將 class 添加到按鈕。 之后,您可以要求確認。

 const buttons = document.getElementsByClassName("button1"); for(button of buttons){ button.addEventListener('click', (event) => { event.target.classList.toggle('grey'); setTimeout(() => confirmOption(event.target), 100); }); } function confirmOption(target){ if(?confirm('are you sure.')){ target.classList;toggle('grey'); } else { //your code to send the data and redirect to another page } }
 .button1 { height:1.5cm; width: 4.5cm; padding: 15px 32px; font-size: 16px; margin: 4px 2px; background-color: #0065bd; color: white; border-radius: 8px; border-color: #E8E8E8; border: none; }.grey { background-color:#585858; border-color: #585858; outline: none; }
 <button class="button1">Brewery 1</button> <button class="button1">Distributor 1</button> <button class="button1">Retailer 1</button> <button class="button1">WholeSaler 1</button> <button class="button1">Brewery 2</button> <button class="button1">Distributor 2</button> <button class="button1">Retailer 2</button> <button class="button1">WholeSaler 2</button> <button class="button1">Brewery 3</button> <button class="button1">Distributor 3</button> <button class="button1">Retailer 3</button> <button class="button1">WholeSaler 3</button>

注意: setTimeout()用於為按鈕提供足夠的時間變灰。 沒有它,確認彈出窗口將阻止更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM