我一直在尝试在我的 html 页面上更改样式以使用此 API 进行存储。我对此很陌生,所以我不确定问题是什么。当我选择菜单项时,样式更改会起作用,但如果我刷新或关闭窗口,它们不会保存。
编辑:我已经不再试图让它们保存,而是使用 localStorage 存储最后使用的样式,然后使用开关运行最后保存的样式的函数。但是,在尝试获取最后保存的值时,我遇到了一个未定义的错误。
这是JS:
//Style 1
function style1(){
var vP = document.getElementById('video_container');
var bG = document.getElementsByTagName('body');
var sidebar = document.getElementById('sidebar');
var banner = document.getElementById('top_header');
var body = document.getElementById('body_div');
vP.style.backgroundColor = ('black');
bG[0].style.background = "url('images/bg/bg1.jpg') no-repeat center center fixed";
sidebar.style.display = ('block');
banner.style.display = ('block');
body.style.marginTop = ('190px');
var selectedStyle = "style";
var value = 's1';
newItem(selectedStyle,value);
}
//Style 2
function style2(){
var vP = document.getElementById('video_container');
var bG = document.getElementsByTagName('body');
var sidebar = document.getElementById('sidebar');
var banner = document.getElementById('top_header');
var body = document.getElementById('body_div');
vP.style.backgroundColor = get_random_color();
bG[0].style.background = "url('images/bg/bg"+randNum()+".jpg') no-repeat center center fixed";
sidebar.style.display = ('block');
banner.style.display = ('block');
body.style.marginTop = ('190px');
var selectedStyle = 'style';
var value = 's2';
newItem(selectedStyle,value);
}
//Style 3
function style3(){
var vP = document.getElementById('video_container');
var bG = document.getElementsByTagName('body');
var sidebar = document.getElementById('sidebar');
var banner = document.getElementById('top_header');
var body = document.getElementById('body_div');
vP.style.backgroundColor = get_random_color();
bG[0].style.background = "url('images/bg/bg"+randNum()+".jpg') no-repeat center center fixed";
sidebar.style.display = ('none');
banner.style.display = ('none');
body.style.marginTop = ('80px');
var selectedStyle = 'style';
var value = 's3';
newItem(selectedStyle,value);
}
//-------------Web Storage API stuff-------------//
window.addEventListener('load',initiate);
function initiate(){
window.addEventListener('storage', storagechange);
show();
}
function newItem(id,style){
localStorage.setItem(id,style);
}
function show(){
var x = localStorage.key(0);
var y = localStorage.getItem(x);
var z=2;
alert(y); //used to test what value i would get, it says undefined
switch (y) {
case 's3':
style3();
break;
case 's2':
style2();
break;
case 's1':
default:
style1();
break;
}
}
HTML:
<div id="sideMenu" >
<ul class="bmenu">
<li id="f1" onclick="style1()">Style 1</li> <!--turn sidebar on/off-->
<li id='f2' onclick="style2()">Style 2</li> <!--randomize vidcontain border-->
<li id='f3' onclick="style3()">Style 3</li>
</ul>
</div>