我有一个包含单元格的表格,单击它们会将单元格的背景颜色更改为绿色。但是,当我重新加载页面时,背景颜色会恢复为原始颜色;白色。有什么方法可以阻止它恢复吗?点击它后要保持绿色?
JS:
function eight(){
var eight = document.getElementById("eight");
eight.style.backgroundColor = "green";
}
HTML:
<td id="eight" onclick="eight(); ">
<a>8</a>
<br>
<center>-</center>
<br>
<center>-</center>
<hr>
<center>-</center>
<br>
<center>-</center>
</td>
*忽略<td>
代码中的内容。
答案 0 :(得分:4)
您必须将颜色值存储在客户端Cookie 或服务器端会话中。现代浏览器也支持 localStorage ..
试试此代码..
function changeBackground() {
if (sessionStorage.getItem('colour')) {
document.body.style.backgroundColor = sessionStorage.getItem('colour');
}else{
document.body.style.backgroundColor = "#BB0A21";
sessionStorage.setItem('colour', "#BB0A21");
}
}
// then you'll need to call your function on page load
changeBackground();
答案 1 :(得分:1)
正如@Yasin所说
使用localstorage.take全局变量
首先向所有单元格添加一个类
假设color.then
var cells=document.getElementsByClassname('color');
var colours=[];
if(localstorage.getItem('colours'))
{
colours = JSON.parse(localstorage.getItem('colours')); // if alreay there
for(i=0;i<cells.length;i++)
{
for(j=0;j<colours.length;j++)
{
if(cells[i].getAttribute('id')==colours[j].id)
{
cells[i].style.backgroundColor = colours[j].colour;
}
}
}
}
function eight(){
var eight = document.getElementById("eight");
eight.style.backgroundColor = "green";
colours.push({id:'eight',colour:'green'});
localstorage.setItem('colours',JSON.stringify(colours));
}
答案 2 :(得分:1)
我已经尝试过一种方法来实现你提供的请求,sessionStorage应该是最适合你的解决方案,但是无论如何cookie都能做到,但是html5支持Web存储,这里有我的演示。
<html DOCTYPE>
<head>
<title>hello world</title>
</head>
<body>
<style type="text/css">
#t1{
background-color: aliceblue;
}
</style>
<table id="t1" onclick="eight();">
<tr>
<td>hello world</td>
</tr>
<tr><td>hello world</td></tr>
<tr><td>hello world</td></tr>
</table>
</body>
<script type="text/javascript">
(function(){
var t = document.getElementById("t1");
window.addEventListener("load", function(){
var color = window.sessionStorage.getItem("tableColor");
if(color == 'undefined'){
t.style.backgroundColor = "aliceblue";
}else if(color == "green"){
t.style.backgroundColor = color;
}else{
alert("another color you have chosen");
}
}, false);
})()
function eight(){
var eight = document.getElementById("t1");
eight.style.backgroundColor = "green";
window.sessionStorage.setItem("tableColor", "green");
}
</script>
</html>
单击表格并重新加载页面后即可。该颜色将保持以前的状态,只有当您关闭浏览器并再次重新打开此页面时,表格背景才会更改为原始状态。