如何在页面重新加载时保持背景颜色变化?
问题描述:
我有一个包含单元格的表格,单击它们会将单元格的背景颜色更改为绿色。但是,当我重新加载页面时,背景颜色会恢复为原始颜色;白色。有什么方法可以阻止它恢复吗?点击它后让它保持绿色?
I have a table which contain cells that when clicked, will change the cell's background color to green. When I reload the page, however, the background color reverts back to its original color; white. Is there any way I can prevent it from reverting? To just keep it green after I clicked it?
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> $ c $内的内容c>标签。
答
您必须将颜色值存储在客户端Cookie 或服务器端会话。现代浏览器也支持 localStorage ..
You have to store the color value in Client side Cookie or Server Side Session. Modern browsers supports localStorage also..
尝试此代码..
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();