Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - 颜色切换按钮(Color switching button)

I wanted to build a Javascript code which changes the background color of the body when a button is clicked.(我想构建一个Javascript代码,当单击一个按钮时,它会更改主体的背景颜色。)

The console says that body.style.background is not a function.(控制台说body.style.background不是函数。) Can you tell what was the mistake in my code?(您能告诉我代码中的错误吗?) var btn = document.querySelector("button"); var body = document.querySelector("body"); var colors = ["red", "blue", "green", "yellow", "orange", "pink"]; var i = 0; btn.addEventListener("click", function(){ if (i < colors.length) { i++; } else if (i == colors.length) { i = 0; } body.style.background("colors[i]"); });   ask by AKHIL REDDY translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to do body.style.background = colors[i];(您需要执行body.style.background = colors[i];)

as background is a property of style so it should be assigned with the value of the color instead of calling it as a function and passing argument into it.(因为backgroundstyle的属性,所以应该为它分配颜色的值,而不是将其作为函数调用并将参数传递给它。) var btn = document.querySelector("button"); var body = document.querySelector("body"); var colors = ["red", "blue", "green", "yellow", "orange", "pink"]; var i = 0; btn.addEventListener("click", function(){ if (i < colors.length) { i++; } else if (i == colors.length) { i = 0; } body.style.background = colors[i]; }); <body> some content <button>Click</button> </body> You can further refactor your code to look much simpler:(您可以进一步重构代码,使其看起来更简单:) var btn = document.querySelector("button"); var body = document.querySelector("body"); var colors = ["red", "blue", "green", "yellow", "orange", "pink"]; var i = 0; btn.addEventListener("click", function(){ i = i < colors.length ? ++i : 0; body.style.background = colors[i]; }); <body> some content <button>Click</button> </body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...