Changing Background colour with Javascript and keeping it after refreshing the page

余生长醉 提交于 2020-01-16 00:43:21

问题


I'm changing the colour of the background when a button is clicked with Javascript.

This is the JS code:

<script>
function myFunction() {
    document.body.style.backgroundColor = "#BB0A21";
}
</script>

It works fine, but the problem is that when the user refreshes the page, the background colour is being reset to the original colour. Is there a way to stop this from happening?

Thanks, Lisa


回答1:


You have to store the color value in Client side Cookie or Server Side Session. Modern browsers supports localStorage also




回答2:


you can store the colour change in a local session. You'll need to check if the session already has the value, setting it if not. this will survive page refreshes etc

    function myFunction() {
        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
  myFunction();


来源:https://stackoverflow.com/questions/31208572/changing-background-colour-with-javascript-and-keeping-it-after-refreshing-the-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!