如果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;
}());
}
像你一樣,請不要使用數組構造函數:,而不是寫'新的Array()',使用的文字符號:'[]'。短得多,更可預測。對象也一樣:使用'{}'而不是'new Object' –