在重新加载时更改div的背景颜色
我想在每次窗口重新加载时更改为div类的背景颜色。
我已经使用此代码在刷新时更改了正文的背景颜色:
但是我想改变’.three’的背景颜色,所以每次窗口重新加载(从颜色数组中选择)时,每个具有’三级’的div将具有不同的背景颜色。
似乎无法弄清楚如何做到这一点,它是否可能?
用这个
var bgcolorlist=new Array("silver", "#BAF3C3", "#c3baf3") $(".three").css("background-color",bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]);
如果必须更改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; }()); }
使用JQuery,你可以做到
$(document).ready(function(){ $('.three').css('background-color',bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)); });
var bgcolorlist = ['silver', '#BAF3C3', '#C3BAF3']; $(function() { $('.three').css({ background: bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)] }); });
每次加载页面时,都会从列表中选择一个随机颜色并将其设置在正文的css上。
通过使用纯JS:
window.onload = function(){ var arr = document.querySelectorAll(".three"); for(var i=0;i
这将为所有div提供三级随机颜色。 如果您希望所有内容都相同,只需将math.random缓存到变量即可