JavaScript函数在Firefox上运行良好但在Chrome上运行良好

lro*_*408 3 javascript

我有一个javascript函数,点击按钮改变导航栏的颜色.我使用了验证器,它没有返回任何错误.我在两个浏览器上都使用了验证器.这是代码的一部分,任何建议将不胜感激.

<body class ="backgroundTwo">
        <h1 class ="centered sansSerif background" >Hello World!</h1>
        <div>
            <ul class ="center">
                <li class ="center"><a id="demo" class ="center"        href="about.html" >About This Site</a></li>
               <li class ="center"><a id ="demo2" class="center" href="current.html">Current Work</a></li>
               <li class ="center"><a id ="demo3" class="center" href="http://www.dallascowboys.com/">Cowboys</a><li>

            </ul> 
        </div>

        <h1 class = "centered" > <img src ="image.jpg" alt = "Cowboys" style="width:304px;height:228px;"></h1>
        <p class = "centered sansSerifTwo" >This is lrodrig6's CSC412 WebSite Project</p>
        <div class ="wrapper">
            <button class="button" onclick="colorFunction()">click    me</button>
        </div>
        <script>
            function colorFunction(){
             var color3 = document.getElementById("demo").style.backgroundColor;
             var color2 = document.getElementById("demo2").style.backgroundColor;
             var color  = document.getElementById("demo3").style.backgroundColor;

                if (color === "lightblue" && color2 === "lightblue" && color3 === "lightblue"){
                    document.getElementById("demo").style.backgroundColor = "white";
                    document.getElementById("demo2").style.backgroundColor = "white";
                  document.getElementById("demo3").style.backgroundColor = "white";
            } else {
                    document.getElementById("demo").style.backgroundColor = "lightblue";
                document.getElementById("demo2").style.backgroundColor = "lightblue";
                document.getElementById("demo3").style.backgroundColor = "lightblue";
               }
        }    
       </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

650*_*502 6

当您设置元素的样式属性(例如style.backgroundColor)时,"lightblue"您不能期望将其读回"lightblue".

例如,chrome返回"rgb(173, 216, 230)".

您需要保留一个变量来存储当前状态,而不是依赖于回读样式属性.

读取和写入属性style不像访问Javascript对象的常规成员.这些操作等同于对getPropertyValueand的调用,setProperty并且您无法保证设置时传递的值与检索时返回的值相同.

例如,"rgb(1,2,3)"你也可能会回来"rgb(1, 2, 3)"(带空格).如果你将一个属性设置为无效的东西(你永远不会从属性中读取一些无效的东西),这是非常明显的.

如果需要在HTML元素中存储逻辑状态,则可以使用为此用法准确引入的数据属性.

在你的具体情况下,例如我会写一些类似于:

var color = "lightblue"; // Using a regular variable to store status

function colorFunction(){
    // Toggle color
    color = (color === "lightblue") ? "white" : "lightblue";
    document.getElementById("demo").style.backgroundColor = color;
    document.getElementById("demo2").style.backgroundColor = color;
    document.getElementById("demo3").style.backgroundColor = color;
}
Run Code Online (Sandbox Code Playgroud)