简体   繁体   中英

How to carry across changes made to a CSS style over different pages

So I'm making a website, with several pages calling on the same CSS file. I am incorporating a method to change the background image of the site. I've got it working locally on each page using the javascript function:

function bgChange(bg) {
    document.body.style.background = bg;
}

Defined in the script section, then implementing it:

<a href="#" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('switchon','','images/switchonhl.jpg',1)" onclick="bgChange(this.style.backgroundImage)"
            style="background-image:url('images/woodbacklight.jpg')"><img src="images/switchon.jpg" width="50" height="50" id="switchon"></a>

However when you go to a different page on the site, it reverts to the original image. Is there a way of keeping the setting across the different pages?

Thanks!

My first thought is localStorage but localStorage can be modified directly on the client. If that is fine with you then it's my first recommendation (as it's quite easy to work with in my experience).

Some of the possible ways of storing data on the client:

  1. Local Storage
  2. Session Storage
  3. Cookies

Some of the possible ways of storing data on the server:

  1. MySQL
  2. MongoDB
  3. Redis

An example use of localStorage (on each page)

(function () {
    // default background image
    if (!localStorage['bg']) localStorage['bg'] = "/path/to/some/default_image.png";

    document.body.style.background = localStorage['bg'];
})();

And then to set the variable:

function changeBg(bg) {
    localStorage['bg'] = bg;
};

first edit your code to save bg in localStorage(or cookies or sessionStorage)

  function bgChange(bg) {
        document.body.style.background = bg;
        localStorage.setItem('bgcolor', bg);
    }

and add this to on page load of every page that you have.

document.onload = function(){
    bg = localStorage.getItem('bg');
    document.body.style.background = bg;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM