功能要求:使用Web存储中的localStorage技术可以把用户对用网页主题样式设置的内容永久存储下来。本例将实现一个网页设置页面,用户可以自定义页面的主题颜色与字体风格并将其存储在localStorage中,当重新加载该页面时会显示上一次保存的样式要求。运行效果如图所示(当选择颜色保存后变成选择颜色)
localStorage方法用于在客户端永久存储数据,该方法存储的数据没有过期时间,即使关闭了浏览器重新打开,数据也仍然保存在设备中可继续使用。
sessionStorage方法和localStorage方法的语法结构均类似,只不过sessionStorage方法有时间限制,只能用于在浏览器打开的时间段(又称为一个session)中存储数据,若浏览器关闭则数据全部消失。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div class="big">
<div id="demo" style="display:flex;width:100%;height:200px;align-items: center;
justify-content: center; color: white">HTML5 Web存储示例</div>
<div id="frame" style="background-color: #EEEEEE; width: 50%;height: 200px;
position: absolute; left:50%;top:50%; transform: translate(-50%, -50%); " >
<form action="">
<div style="height: 30px"> </div>
<div id="page" style=" display:flex;width:100%; align-items: center;
justify-content: center;color: white ">页面设置</div>
<div style=" display:flex;width:100%; align-items: center;
justify-content: center;">主题颜色为:
<select name="" id="color" >
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select>
</div>
<br>
<div style=" display:flex;width:100%; align-items: center;
justify-content: center;"> <button οnclick="saveLocal()">保存并设置</button></div>
<div id="page2"></div>
</form>
</div>
<div id="bottom" style=" display:flex;width:100%;height:100px;position:fixed;bottom: 0; align-items: center;
justify-content: center;color: white ">Copyright ©:ZWJ 2016-2020 ALL Rights Reserved</div>
</div>
</body>
<script>
let page = document.getElementById('page');
let demo = document.getElementById('demo');
let bottom = document.getElementById('bottom');
function saveLocal() {
var color = document.getElementById('color').value;
alert("数据已保存到localstorage,当前颜色:"+color)
localStorage.setItem('color',color);
}
var pageColor = localStorage.getItem('color');
page.style.backgroundColor=pageColor;
demo.style.backgroundColor=pageColor;
bottom.style.backgroundColor=pageColor;
</script>
</html>