问题
I've got this in my code, which should select a random background colour every refresh, but i can't see what's wrong with my document.write
var bgcolorlist=new Array("#ff871b", "#15efa1", "#51ddff", "#ff1b6c", "#000000")
document.write('<meta name="color:Background" content='+background=bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)] + '>')
Cheers!
回答1:
You need semicolons after each line.
Additionally, why are you seeing the background color with a meta tag?
Use this line instead:
document.body.style.backgroundColor = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
回答2:
Another solution is to add an ID to your body and then use this code:
<script>
var bgcolorlist=new Array("background: #ff871b", "background: #15efa1", "background: #51ddff", "background: #ff1b6c", "background: #000000");
var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
var d = document.getElementById("your-body");
d.setAttribute("style", color);
</script>
As far as I know, Tumblr allows you to use jQuery, which is way easier than pure Javascript. If you have jQuery added to your code, just do:
<script>
var bgcolorlist=new Array("background: #ff871b", "background: #15efa1", "background: #51ddff", "background: #ff1b6c", "background: #000000");
var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
$('body').css('backgroundColor', color);
</script>
来源:https://stackoverflow.com/questions/18116470/random-background-colour-picker-for-tumblr