JavaScript - 用普通 JavaScript 切换 CSS 颜色?

JavaScript - Toggle CSS colors with plain JavaScript?

我正在尝试使用普通 javascript 来回更改表单文本字段的颜色。有人可以帮忙吗?

我可以改一次颜色但不能改回来

这是我所做的

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript</title>

    </head>

    <body>
        <script type="text/javascript">
            function color() {
                var x = document.getElementById("currID");
                if(x.style.color="red") {
                    x.style.color="blue";
                 }    
                }

            }
        </script>

        <input type="button" value="Click Me" id="testButton" onclick="color()" />

        <form method="get" action="getresult.php">

            <p>Current ID: <input id="currID" class="a" type="text" name="currID" /></p>
        <p><input type="submit" value="Request new ID"/></p>


        </form>

    </body>
</html>

CSS

<style type="text/css">
                .main {
                    color:black;
                }
                .a {
                    color:red;
                }
            </style>

试试这个:

    <!DOCTYPE html>
<html>
<head>
    <title>JavaScript</title>

</head>

<body>
    <script type="text/javascript">
           function color() {
            var x = document.getElementById("currID");
                if(x.className == "main"){
                    x.className = "a";
                } else {
                    x.className = "main";
                }
            }
    </script>

    <input type="button" value="Click Me" id="testButton" onclick="color()" />

    <form method="get" action="getresult.php">

        <p>Current ID: <input id="currID" class="a" type="text" name="currID" /></p>
    <p><input type="submit" value="Request new ID"/></p>


    </form>

</body>
</html>

CSS:

<style type="text/css">
.main {
    color:black;
}
.a {
    color:red;
}
</style>

演示:https://jsfiddle.net/a5rxoh03/

特别针对您的问题,以及为什么它不起作用,是因为在添加第二个 IF 时,您只是推翻了结果。

查看此 fiddle,它将根据要求将 "currID" 的输入字段从蓝色更改为红色,反之亦然。

https://jsfiddle.net/0rnnqe3y/

这是 JS :

         function color() {
            var x = document.getElementById("currID");
            console.log(x.style.color == "red");
            if(x.style.color=="red") {

                x.style.color="blue";
                return;

             };
            if(x.style.color=="blue"){
               x.style.color="red";
               return;
            }   
}