如何在页面重新加载时保持背景颜色变化? [英] How to keep background color changes on page reload?

查看:106
本文介绍了如何在页面重新加载时保持背景颜色变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含单元格的表格,单击它们会将单元格的背景颜色更改为绿色。但是,当我重新加载页面时,背景颜色会恢复为原始颜色;白色。有什么方法可以阻止它恢复吗?点击它后让它保持绿色?

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> 标签。

推荐答案

您必须将颜色值存储在客户端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();

这篇关于如何在页面重新加载时保持背景颜色变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆