在重新加载时更改div的背景颜色

时间:2012-11-29 12:11:01

标签: javascript jquery css

每次窗口重新加载时,我都希望更改为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>

但是我想改变'.three'的背景颜色,所以每次窗口重新加载(从颜色数组中选择)时,每个具有类'three'的div将具有不同的背景颜色。
似乎无法弄清楚如何做到这一点,是不是很有可能?

5 个答案:

答案 0 :(得分:1)

使用此

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

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

答案 1 :(得分:1)

如果要更改bg-color ,您可以使用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;
    }());
}

答案 2 :(得分:0)

使用JQuery可以做到

$(document).ready(function(){
    $('.three').css('background-color',bgcolorlist[Math.floor(Math.random()*bgcolorlist.length));
});

答案 3 :(得分:0)

var bgcolorlist = ['silver', '#BAF3C3', '#C3BAF3'];

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

每次加载页面时,都会从列表中选择一种随机颜色并将其设置在正文的css上。

答案 4 :(得分: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缓存到变量

相关问题