简体   繁体   English

将 style.background 设置为 var 不起作用

[英]Setting style.background as a var doesn't work

I modified this working Javascript code by setting style.background as var "x" and it doesn't toggle anymore.我通过将 style.background 设置为 var "x" 修改了这个工作Javascript 代码,它不再切换。 Where is the problem?问题出在哪儿?

<script>
var myVar = setInterval(setColor, 300);
 
function setColor() {
/* This commented-out code works.
  var x = document.body;
  x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
  */
  var x = document.body.style.backgroundColor;  // not working
  x = x == "yellow" ? "pink" : "yellow";
}
</script>

Your assigning value to variable "x", not document.body.style.backgroundColor , don't store it in a variable.您将值分配给变量“x”,而不是document.body.style.backgroundColor ,不要将其存储在变量中。

 <script> var myVar = setInterval(setColor, 300); function setColor() { var x = document.body.style.backgroundColor; // not working document.body.style.backgroundColor = x == "yellow" ? "pink" : "yellow"; } </script>

That's because in the original code:那是因为在原始代码中:

function setColor() {
  var x = document.body;
  x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}

x is a reference of document.body, nevertheless, in your code, when you do: x 是 document.body 的引用,但是,在您的代码中,当您执行以下操作时:

x = x == "yellow" ? "pink" : "yellow";

x is not equal to a reference of document.body anymore, now it is a string, either pink or yellow. x 不再等于 document.body 的引用,现在它是一个字符串,粉红色或黄色。 So, x will not change the html because it is only a string variable.所以, x 不会改变 html 因为它只是一个字符串变量。

If you want the code to work, you need to add this code behind x declaration.如果你想让代码工作,你需要在 x 声明后面添加这段代码。

document.body.style.backgroundColor = x

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

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