如果必须更改背景颜色,您可以使用localStorage
在重新加载页面之前检查背景颜色:
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;
}());
}