版权声明:本文章博主原创,希望对你有所帮助。 https://blog.csdn.net/sakenc/article/details/90631875
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body onload="colorload()">
<script type="text/javascript">
// 检测浏览器是否支持localStorage。
if (typeof localStorage === 'undefined') {
window.alert("您的浏览器不支持localStorage。");
} else {
window.alert("您的浏览器支持localStorage。");
var storage = localStorage;
// 设置DIV背景颜色为红色,并保存localStorage。
function redSet() {
var value = "red";
document.getElementById("divblock").style.backgroundColor = value;
window.localStorage.setItem("DivBackGroundColor", value);
}
// 设置DIV背景颜色为绿色,并保存localStorage。
function greenSet() {
var value = "green";
document.getElementById("divblock").style.backgroundColor = value;
window.localStorage.setItem("DivBackGroundColor", value);
}
// 设置DIV背景颜色为蓝色,并保存localStorage。
function blueSet() {
var value = "blue";
document.getElementById("divblock").style.backgroundColor = "blue";
window.localStorage.setItem("DivBackGroundColor", value);
}
function colorload() {
document.getElementById("divblock").style.backgroundColor = window.localStorage.getItem("DivBackGroundColor");
}
}
</script>
<section id="main">
<button id="redbutton" onclick="redSet()">红色</button>
<button id="greenbutton" onclick="greenSet()">绿色</button>
<button id="bluebutton" onclick="blueSet()">蓝色</button>
</section>
<div id="divblock" style="width:500px; height:500px;"></div>
</body>
</html>