2012-11-29 55 views
0

我期待每次重新加载窗口时都更改为div类的背景颜色。
我用这个代码来改变身体的背景颜色上刷新:
更改div的背景颜色在重新加载

<script type="text/javascript"> 
<!-- //Enter list of bgcolors: 
var bgcolorlist=new Array("silver", "#BAF3C3", "#c3baf3") 

document.body.style.background=bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)] 
// --> 
</script> 

但我希望改变,因此与类“三每格的“三”的背景颜色'在每次重新加载窗口时都会有不同的背景色(从一组颜色中进行选择)。
似乎无法弄清楚如何做到这一点,是否有可能?

+0

像你一样,请不要使用数组构造函数:,而不是写'新的Array()',使用的文字符号:'[]'。短得多,更可预测。对象也一样:使用'{}'而不是'new Object' –

回答

1

使用此

var bgcolorlist=new Array("silver", "#BAF3C3", "#c3baf3") 

$(".three").css("background-color",bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]); 
0

使用jQuery你可以做

$(document).ready(function(){ 
    $('.three').css('background-color',bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)); 
}); 
0
var bgcolorlist = ['silver', '#BAF3C3', '#C3BAF3']; 

$(function() { 
    $('.three').css({ 
     background: bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)] 
    }); 
}); 

每次页面加载,这个挑选从列表中随机颜色,并将其对人体的CSS。

0

通过使用纯JS:

window.onload = function(){ 
    var arr = document.querySelectorAll(".three"); 
    for(var i=0;i<arr.length;i++){ 
     arr[i].style.background = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)] 
    } 
} 

这将给与三级随机颜色的所有div。如果您希望所有要一样,只是缓存的Math.random给一个变量

1

如果BG-颜色改变,你可以使用localStorage检查BG为被重新加载之前,页面的内容:

var colours = ['#F00','#0F0'];//my eyes! 
var currentColour = +(localStorage.previousBGColour || -1)+1; 
currentColour = currentColour >= colours.length ? 0 : currentColour;//if index is not set reset to colour at index 0 
document.getElementById('theDiv').style.backgroundColor = colours[currentColour]; 
localStorage.previousBGColour = currentColour;//store colour that's currently in use 

注意,并不是所有的浏览器都支持localStorage:有些人还在使用旧,照出IE8,例如。

的jQuery

$(document).ready(function() 
{ 
    (function() 
    {//this IIFE is optional, but is just a lot tidier (no vars cluttering the rest of the script) 
     var colours = ['#F00','#0F0'], 
     currentColour = +(localStorage.previousBGColour || -1) + 1; 
     $('#theDiv').css({backgroundColor:colours[currentColour]}); 
     localStorage.previousBGColour = currentColour; 
    }()); 
}