简体   繁体   English

如何在不同页面上进行对CSS样式的更改

[英]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. 因此,我正在创建一个网站,其中有多个页面调用相同的CSS文件。 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: 我已经使用javascript函数在每个页面上本地工作:

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. 我的第一个想法是localStorage,但是可以直接在客户端上修改localStorage。 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 的MySQL
  2. MongoDB MongoDB
  3. Redis 雷迪斯

An example use of localStorage (on each page) 使用localStorage的示例(在每个页面上)

(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) 首先编辑您的代码以将bg保存在localStorage(或cookie或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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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