admin管理员组文章数量:1395291
I am having some trouble changing the color of the background on each refresh. Any help is appreciated. Here is my js so far:
var colors = ['#760CE8', '#4782B1', '#E8890C'];
var changeBackground = function() {
document.body.style.background = colors([Math.floor(Math.random()*colors.length)]);
};
changeBackground();
I am having some trouble changing the color of the background on each refresh. Any help is appreciated. Here is my js so far:
var colors = ['#760CE8', '#4782B1', '#E8890C'];
var changeBackground = function() {
document.body.style.background = colors([Math.floor(Math.random()*colors.length)]);
};
changeBackground();
Share
Improve this question
edited Apr 22, 2014 at 5:25
takendarkk
3,4428 gold badges27 silver badges38 bronze badges
asked Apr 22, 2014 at 5:22
WaymondWaymond
2572 gold badges6 silver badges21 bronze badges
2 Answers
Reset to default 4You're almost there.
In the line
document.body.style.background = colors([Math.floor(Math.random()*colors.length)]);
you need to remove the parentheses surrounding [Math.floor(Math.random()*colors.length)]
.
Otherwise JS will think that you want to invoke colors
as a function.
Instead you want to access an array by index. That's what the square brackets do.
So change it to
document.body.style.background = colors[Math.floor(Math.random()*colors.length)];
and it will be fine.
Your code is fine just do as @TheShellfishMeme said and put your function in the body tag like this:
<body onload="changeBackground();">
now on every refresh you get the different body color.
本文标签: javascriptChange background color on refresh with Vanilla JSStack Overflow
版权声明:本文标题:javascript - Change background color on refresh with Vanilla JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744666432a2618560.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论