添加Cookie以输入背景颜色更改 [英] Add Cookies To Input Background Color Change

查看:361
本文介绍了添加Cookie以输入背景颜色更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的网站添加了背景颜色更改效果。现在我想要该更改应用于我所有的其他页面。我有麻烦理解cookie函数,所以一些上下文与我正在工作真的会有帮助。

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.

我的JS:

函数背景(color){document.body.style.backgroundColor = color;}

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

我的HTML:

< tr>< td class =bggreenstyle = cursor:pointeronclick =background('green')>& nbsp;< / td>< / tr>

我的CSS:

.bggreen {background-color:green; }

代码一切正常,所以一些信息可能是无意义的。只是,如果我构建一个cookie来使这些颜色更改适用于我的网站中的所有相关页面,我该怎么办?没有偏好是否使用PHP或JS。

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.

推荐答案

这里有一些简单的cookie函数我使用javascript。您可以在cookie中存储最新的颜色值,然后在页面初始化时,您可以从cookie中读取值并正确设置颜色:

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);
}

code> value 是字符串。 days 是Cookie过期前的天数。

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;
}

这篇关于添加Cookie以输入背景颜色更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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