cos*_*smo 4 html javascript css
我有一个表格,其中包含单元格,单击该单元格会将单元格的背景色更改为绿色。但是,当我重新加载页面时,背景颜色会恢复为原始颜色。白色。有什么办法可以防止它还原?要在单击后使其保持绿色?
JS:
function eight(){
var eight = document.getElementById("eight");
eight.style.backgroundColor = "green";
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<td id="eight" onclick="eight(); ">
<a>8</a>
<br>
<center>-</center>
<br>
<center>-</center>
<hr>
<center>-</center>
<br>
<center>-</center>
</td>
Run Code Online (Sandbox Code Playgroud)
*忽略<td>标签内的内容。
小智 5
您必须将颜色值存储在客户端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();
Run Code Online (Sandbox Code Playgroud)