简体   繁体   中英

How to change the font color of an user input value (prompt) in JavaScript?

How can I change the color of the value of the variable number ( nb )? How can I change the font color of an user input value (prompt) in JavaScript?


<html>
    <head>
        <style>
            #block{
                color: white;
                width: 300px;
                height: 60px;
                background-color: #2b2e2e;
                text-align: center;
                padding-top: 30px;
            }
        </style>
    </head>
    <body>
        <div id="block">
            
        </div>
        <script>
            window.onload = function printNumber(){
                var unBlock = document.getElementById("block");
                var nb = Number(prompt("Saisir un nombre: "));
                
                if(nb == null || nb == ""){
                    unBlock.innerHTML = "No input number.";
                }else{
                    unBlock.innerHTML = "Your input number is "+nb;
                }
                
            }
        </script>
    </body>
</html>

The code below illustrates two ways.

  1. By creating a span with colored as its class, it turns it blue.
  2. Subsequently, in my code, I'm overriding that by turning it red using javascript.

Either of those methods will work, but you only need one, not both. I used both just for illustration of your options.

 window.onload = function printNumber() { var unBlock = document.getElementById("block"); var nb = Number(prompt("Saisir un nombre: ")); if (nb == null || nb == "") { unBlock.innerHTML = "No input number."; } else { unBlock.innerHTML = `Your input number is <span class='colored'>${nb}</span>`; //the next line will select your span and override blue with red. document.querySelector("span.colored").style.color = 'red'; } }
 #block { color: white; width: 300px; height: 60px; background-color: #2b2e2e; text-align: center; padding-top: 30px; } span.colored { color: blue; }
 <div id="block"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM