我有一个 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>
最佳答案
当您将元素的样式属性(例如 style.backgroundColor
)设置为 "lightblue"
时,您不能期望将其读回为 "lightblue"
。
例如,chrome 返回 "rgb(173, 216, 230)"
。
您需要保留一个变量来存储当前状态,而不是依赖于回读样式属性。
style
的读写属性与访问 Javascript 对象的常规成员不同。这些操作等同于调用 getPropertyValue
和 setProperty
,您无法保证设置时传递的值与检索时返回的值相同。
例如,传递 "rgb(1,2,3)"
也有可能返回 "rgb(1, 2, 3)"
(带空格).如果您将属性设置为无效的东西(您永远不会从属性中读取无效的东西),这也是绝对明显的。
如果您需要在 HTML 元素中存储逻辑状态,您可以使用 data attributes正是为这种用法而引入的。
例如,在您的具体情况下,我会这样写:
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;
}
关于JavaScript 函数在 Firefox 上运行良好但在 Chrome 上运行不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33050861/