頁面切換主題風格,利用本地緩存
//默認為黑色主題,全局變量
var saveThemeColor = {
‘Name‘: ‘ThemeColor‘,
‘Color‘: ‘darktheme‘
}
var storage = getLocalStorage();
// 判斷用戶是否已有自己選擇的主題風格
if (storageLoad(‘ThemeColor‘)) {
var themecolor = storageLoad(‘ThemeColor‘).Color;
$(‘body‘).attr(‘class‘,themecolor);
} else {
storageSave(saveThemeColor);
$(‘body‘).attr(‘class‘, ‘darktheme‘);
}
// 本地緩存
function storageSave(obj) {
storage.setItem(obj.Name, JSON.stringify(obj));
}
function storageLoad(objectName) {
if (storage.getItem(objectName)) {
return JSON.parse(storage.getItem(objectName));
} else {
return false;
}
}
//兼容ie本地緩存
function getLocalStorage(){
if(typeof localStorage == ‘object‘){
return localStorage;
}else if (typeof globalStorage == ‘object‘) {
return globalStorage[location.host];
} else {
throw new Error(‘Local storage not available‘);
}
}
//切換主題
$(‘.themeli‘).find(‘span‘).on(‘click‘,function(){
$(‘body‘).attr(‘class‘, $(this).attr(‘data-color‘))
saveThemeColor.Color = $(this).attr(‘data-color‘);
// 保存選擇項
storageSave(saveThemeColor);
});
頁面切換主題風格,利用本地緩存