如果用户选择不同的背景图像,如何使背景图像永久化

时间:2014-05-03 16:33:33

标签: javascript php cookies

我有以下的JS,我想制作cookie或其他所以如果用户更改图像,那么它将为整个网站的用户保留相同的背​​景。请帮我解决这个问题。但是当我更改图像时,它会更改图像,但是当我转到另一个页面时,它会返回默认值

<script language="JavaScript">
    var w=screen.width
    var h=screen.height
if(w==1280) {
var backImage = new Array(); // don't change this
backImage[0] = "images/patterns/background-1280x-yellow.png";
backImage[1] = "images/patterns/background-1280x-mellow.png";
backImage[2] = "images/patterns/background-1280x-sellow.png";

function changeBGImage(whichImage){
if (document.body){
document.body.style.backgroundImage = "url("+backImage[whichImage]+")";
}}
}
if(w==1440) {
var backImage = new Array(); // don't change this
backImage[0] = "images/patterns/background-1440x-yellow.png";
backImage[1] = "images/patterns/background-1440x-mellow.png";
backImage[2] = "images/patterns/background-1440x-sellow.png";

function changeBGImage(whichImage){
if (document.body){
document.body.style.backgroundImage = "url("+backImage[whichImage]+")";
}}
}
</script>

<?php
echo "<a href='javascript:changeBGImage(0)'>Yellow - </a>";
echo "<a href='javascript:changeBGImage(1)'>Mellow - </a>";
echo "<a href='javascript:changeBGImage(2)'>Sellow</a>";
//echo "<a href='javascript:changeBGImage(3)'>4</a>";
?>

2 个答案:

答案 0 :(得分:0)

查看JavaScript Cookie。 Here's a good intro from w3schools.

基本上,您要做的是在changeBGImage函数中创建一个cookie,用于存储所选背景的编号,

document.cookie = "bg="+whichImage;

然后,在页面顶部,检查是否存在bg cookie,如果存在,则获取其值并设置背景。

上面的链接应该提供您需要的所有信息。

答案 1 :(得分:0)

听起来你已经知道如何做到这一点,使用cookies。这是我使用的cookie对象:

var cookie = {
    set: function(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=/";
    },
    get: function(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;
    },
    erase: function(name) {
        cookie.set(name,"",-1);
    }
}

这允许简单的调用,例如cookie.set('cookie_name', cookie_value, days);cookie.get('cookie_name');

因此,当用户选择图像时,请致电cookie.set('bgImage', image_url, 365);

function changeBGImage(whichImage){
  if (document.body){
   document.body.style.backgroundImage = "url("+backImage[whichImage]+")";
   cookie.set('bgImage', whichImage, 365);
  }}
}

加载页面时,请检查Cookie是否存在(if(cookie.get('bgImage')))并将背景更改为存储在Cookie中的值。您可以将此行放在脚本块的底部,它应该可以正常工作:

// if they have a cookie set with which image they prefer, call changeBGImage with that value.
if(cookie.get('bgImage')){
   changeBGImage(cookie.get('bgImage'));
}