开发者

User sets BackgroundImage. Store image url in cookie so it loads on next visit

I am working on a website:

htt开发者_如何学Gop://tawfiq-aliyah.co.uk/epic/Site2/

I want the user to be able to set the BackgroundImage. I have implemented this with the pop-up menu in the bottom left hand corner already. But what I want is for the data about the users choice of background image to be stored so that when they come back to the site or move to another page on the site it loads the same background image.

I have looked into java cookies on the w3schools.com website w3schools.com/js/js_cookies.asp

I have looked at the example but I am not sure how to get the cookie to store the backgroundImage of the instead of storing a username.

Any help would be much appreciated. Thanks


In the click handlers for the thumbnails in the background image selector you do things like this:

onclick="main.style.backgroundImage='url(images/back3.jpg)'"

If you replace that with a function:

onclick="setBackgroundImage('images/back3.jpg')"

and then

function setBackgroundImage(url) {
    main.style.backgroundImage = 'url(' + url + ')';
    setCookie('BG', url, 100);    // Or however many days you want.
}

And then, in an onload handler, do something like this:

var bg = getCookie('BG');
if(bg)
    main.style.backgroundImage = 'url(' + bg + ')';

You might want to do more sanity checking on the cookie value though, you have a list of available backgrounds kicking around so you could just check that bg is defined and that it is in the list.

Also, you might want to use absolute URLs for your images rather than relative ones, that makes it easier to move things around.


I've never worked with cookies in javascript, but looking at the w3c exampple you provided, wouldn'nt it be fine to use that technique and just store the url instead of the username? And then set the img:src or background-url or what ever you are using to that url from the getCookie function? (or later, whenever the dom is ready).

An alternative could be to use local storage, but it might be overkill for what you are trying to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜