Add Cookies To Input Background Color Change

瘦欲@ 提交于 2020-01-25 23:45:30

问题


I have added a background color change effect to my website. Now I want that change to apply to all my other pages. I'm having trouble understanding cookie functions, so some context with what I'm working on would really help.

My JS:
function background(color){document.body.style.backgroundColor=color;}

My HTML:
<tr><td class="bggreen" style="cursor: pointer" onclick="background('green')">&nbsp;</td></tr>

My CSS:
.bggreen { background-color: green; }

The code all works fine, so some of this info might be pointless. It's just, if I were to construct a cookie to make these color changes apply to all relevant pages in my site, how would I go about? No preference to whether PHP or JS is used. I would just like what comes most practically.


回答1:


Here are some simple cookie functions I use from javascript. You can store the latest color value in the cookie and then upon initialization of the page, you can read the value from the cookie and set the color appropriately:

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

name and value are strings. days is a number of days until the cookie expires.

So, whenever you change the color, you could do this:

function background(color){
    document.body.style.backgroundColor = color;
    createCookie("backgroundColor", color, 365);
}

And, when the page first loads, you could do this:

var color = readCookie("backgroundColor");
if (color) {
    document.body.style.backgroundColor = color;
}


来源:https://stackoverflow.com/questions/20156129/add-cookies-to-input-background-color-change

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