如何使用JavaScript更改所有网站页面的正文背景颜色?



简而言之,我有一个网站 http://myWebSite,其中包含两个页面page1.htmlpage2.html
我在 page1.html 和 page2 的 head 部分中使用 CSS 样式表.html

<link crossorigin="anonymous" rel="stylesheet" href="myStyles.css">

我的样式.css :

body {
background-color: blue;
}

在第 1.html 页上,我使用以下 JavaScript 代码修改当前页面的烘焙颜色:

<script>
document.styleSheets[0].cssRules[0].style.backgroundColor="white";
</script>

正如预期的那样,只有 page1.html 的背景颜色发生了变化。 如何为所有网站页面保留此修改?我想我必须使用饼干。右?我该怎么做?
谢谢你的回答。

设置cookie可以工作。一个稍微好一点/更广泛的解决方案是使用LocalStorage.这样,更改将显示在任何 Web 浏览器中。如果你不熟悉W3Schools,有一个使用LocalStorage的很好的例子:https://www.w3schools.com/html/html5_webstorage.asp

从我的代码中,我有

if (typeof Storage !== 'undefined') {
if (localStorage) localStorage.setItem('bodyclass', color);
}

try {
var bodyClass = localStorage.getItem('bodyclass');
if (bodyClass) $(document.body).addClass(bodyClass);
}
catch (e) {
error.reportError("No local storage support. Changes to body style will not be persistant");
}

不需要使用 cookie(cookie 对服务器有用,对浏览器没有用(。 使用本地存储在本地保存当前背景色。

<!-- page1.html -->
<script>
document.styleSheets[0].cssRules[0].style.backgroundColor="white";
localStorage.backgroundColor = "white";
</script>

在第 2 页中.html您必须从 localStorage 获取属性并使用它设置背景。

<!-- page2.html -->
<script>
var color = localStorage.backgroundColor;
if(color) {
document.styleSheets[0].cssRules[0].style.backgroundColor = color;
}
</script>
document.getElementsByTagName("BODY")[0].setAttribute("style", "color:red; border: 1px solid blue;")

https://jsfiddle.net/d39brzLk/

最新更新