我正在尝试编写基本的JavaScript,将段落的背景更改为黄色,然后在点击时将其更改为粉红色。
<p id="foo">Hello, people!</p>
和脚本是
window.onload = function(){
var foo = document.getElementById("foo");
foo.onclick = function(){
if(foo.style.background!=="yellow")foo.style.background = "yellow";
if(foo.style.background === "yellow") foo.style.background = "pink";
};
};
第一次点击时颜色变为黄色,但再次点击时,不会变为粉红色。我无法弄清楚问题。
答案 0 :(得分:7)
编辑:请勿使用background
,请使用backgroundColor
if(foo.style.background!=="yellow")foo.style.background = "yellow";
if(foo.style.background === "yellow") foo.style.background = "pink";
需要:
if(foo.style.background!=="yellow")foo.style.background = "yellow";
else if(foo.style.background === "yellow") foo.style.background = "pink";
因为您将其更改为黄色,然后检查它是否为黄色并使其变为粉红色
答案 1 :(得分:0)
尝试更改
if(foo.style.background === "yellow")
到这个
if(foo.style.background == "yellow")
答案 2 :(得分:0)
这可能是由于您进行比较的方式:
foo.onclick = function(){ if(foo.style.background != "yellow") foo.style.background = "yellow"; if(foo.style.background == "yellow") foo.style.background = "pink"; };
请注意使用“!=”和“==”而不是“!==”和“===”。
答案 3 :(得分:0)
尝试:
var foo = document.getElementById("foo");
foo.onclick = function(){
if(foo.style.background!="yellow")foo.style.background = "yellow";
else if(foo.style.background =="yellow") foo.style.background = "pink";
};
var foo = document.getElementById("foo");
foo.onclick = function(){
if(foo.style.backgroundColor!="yellow")foo.style.backgroundColor = "yellow";
else if(foo.style.backgroundColor =="yellow") foo.style.backgroundColor = "pink";
};