简体   繁体   English

如何在 JavaScript 中更改用户输入值(提示)的字体颜色?

[英]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 )?如何更改变量编号 ( nb ) 的值的颜色? How can I change the font color of an user input value (prompt) in JavaScript?如何在 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.通过创建一个带有colored作为其类的跨度,它会变成蓝色。
  2. Subsequently, in my code, I'm overriding that by turning it red using javascript.随后,在我的代码中,我通过使用 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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