簡體   English   中英

我如何更改選定的背景顏色輸入 html/js

[英]How i can change the selected background color input html/js

我正在嘗試制作 Rock,Paper,Scissors 游戲,但我想在玩家選擇(例如 Rock)並且他贏了 Input(Rock) 背景顏色更改時進行制作,但我很難做到,因為我是還在學習js

html :

<div id="buttonsInput" class="m-4">
            <input type="image" width="150px" height="150px" src="photo's/r.png" name="rock" class="border border-light rounded-circle rock d-inline m-2" id="Rock">
            <input type="image" width="150px" height="150px" src="photo's/p.png" name="paper" class="border border-light rounded-circle paper d-inline m-2" id="Paper">
            <input type="image" width="150px" height="150px" src="photo's/s.png" name="scissors" class="border border-light rounded-circle scissors d-inline m-2" id="Scissors">
        </div>

js:

function win(userChoice, pcChoice){
    userScore++;
    if(userScore > 5 ){
    userScore = 0;
    pcScore = 0;
    alert("You WIN !");
    location.reload()
    }
    userScore_span.innerHTML = userScore;
    pcScore_span.innerHTML = pcScore;
    const player = "Player".fontsize(4).fontcolor("#dc3545").sup();
    const PC = "PC".fontsize(4).fontcolor("#dc3545").sup();
    const win = "Win!".fontcolor("#28a745")
    result_div.innerHTML = userChoice + player + " Beats "+ pcChoice + PC +" "+ " You "+ win;
}

這是 GitHub: https : //github.com/AppleGamer77/rockpaperscissors

可以通過以下 2 個步驟更改 div 的背景顏色:

第 1 步:更新 CSS

為 3 個結果(獲勝者、松散者、平局)定義這 3 個 CSS 類:

文件名: rps_style.css (將以下新類添加到文件中)

.winner {
    background-color: #b6eac8;
}

.looser {
    background-color: #fa6000;
}

.draw {
    background-color: #ddbbaa;
}

第 2 步:更新 Javascript

更新 Javascript 函數(win、loose、draw)以將適當的 css 類設置為輸入 div

文件名: java.js

function win(userChoice, pcChoice){
    //  existing code 

    // Add the following lines the end of the function
    var myDiv = document.getElementById("buttonsInput")
    if (myDiv.className.indexOf("winner") <= 0) {
        myDiv.className = "m-4 winner";
    }
    
}

function loses(userChoice, pcChoice){

    // existing code 

    // Add the following lines the end of the function
    var myDiv = document.getElementById("buttonsInput")
    if (myDiv.className.indexOf("looser") <= 0) {
        myDiv.className = "m-4 looser";
    }
        
}

function draw(userChoice, pcChoice){

    // existing code 

    // Add the following lines the end of the function
    var myDiv = document.getElementById("buttonsInput")
    if (myDiv.className.indexOf("draw") <= 0) {
        myDiv.className = "m-4 draw";
    }
    
}


輸出:

1.贏:

在此處輸入圖片說明


2. 松:

在此處輸入圖片說明


3. 抽獎:

在此處輸入圖片說明


更多信息: https : //www.w3schools.com/JSREF/prop_html_classname.asp

暫無
暫無

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

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