总而言之,我有一个网站http://myWebSite,其中包含两个页面page1.html和page2.html
我在page1.html和page2.html的头部使用CSS样式表
<link crossorigin="anonymous" rel="stylesheet" href="myStyles.css">
myStyles.css:
body {
background-color: blue;
}
在page1.html上,我使用以下JavaScript代码修改当前页面的背景色:
<script>
document.styleSheets[0].cssRules[0].style.backgroundColor="white";
</script>
与预期的一样,只有page1.html的背景色发生了变化。
如何对所有网站页面保留此修改?我想我必须使用cookie。对 ?我怎样才能做到这一点 ?
感谢您的回答。
最佳答案
设置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");
}