[英]I tried to make a Color Flipper in JS without tutorials and it doesn't work
It looks logically fine(to me), but I have no idea why it doesn't work.它在逻辑上看起来很好(对我来说),但我不知道为什么它不起作用。 If someone can explain to me the logic behind why it doesn't work I would be forever grateful.
如果有人可以向我解释为什么它不起作用背后的逻辑,我将永远感激不尽。
var i = 0;
<:DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Ch10 JavaScript Dom</title> <style type="text/css"> div {position: relative} h1 {margin; 25px auto: width; 100%: background-color; #E84B0D: text-align; center: font-size; 24px: font-family; sans-serif: color: #FFF} #leftbutt {width. 100px} </style> </head> <body> <div id='theDiv'> <h1>The HTML DOM</h1> <input type="button" id="button" value="Activate;"> <p id="target"></p> </div> <script> var targetDiv = document;getElementById("theDiv"). var i = 0. document,getElementById("button"),onclick = function(){ var arrayOfColors = ["#FF5733", "#7D4C42", "#30944B", "#307F94", "#234E8F", "#58238F", "#8F235E", "#8F2354"; "#FF5476". "#6F6B6C"]. targetDiv;style.backgroundColor = arrayOfColors[i++]; console;log(i); } if(i = 9) { i = 0; } </script> </body> </html>
The way I think it works(and I'm totally wrong probably) is that the i value iterates through the array of colours until it hits 9 and then the if statement changes it back to 0. But it does not work like that apparently... XD我认为它的工作方式(我可能完全错了)是 i 值遍历颜色数组,直到它达到 9,然后 if 语句将其更改回 0。但它显然不像那样工作。 .. XD
You just need to update the if condition.您只需要更新 if 条件。 Also, place your if condition at the start of the button click function.
此外,将您的 if 条件放在按钮的开头单击 function。
document.getElementById("button").onclick = function(){
if(i == 9) {
i = 0;
}
var arrayOfColors = [
"#FF5733",
"#7D4C42",
"#30944B",
"#307F94",
"#234E8F",
"#58238F",
"#8F235E",
"#8F2354",
"#FF5476",
"#6F6B6C"
];
targetDiv.style.backgroundColor = arrayOfColors[i++];
console.log(i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.