To summarize very shortly, I have a web site http://myWebSite that contains two pages page1.html and page2.html
I use a CSS style sheet in the head section of page1.html and page2.html
<link crossorigin="anonymous" rel="stylesheet" href="myStyles.css">
myStyles.css :
body {
background-color: blue;
}
On page1.html, I modify the bakground color of the current page with the following JavaScript code :
<script>
document.styleSheets[0].cssRules[0].style.backgroundColor="white";
</script>
As expected, only the background color of page1.html changes. How is it possible to keep this modification for all the web site pages ? I suppose I must use cookies. Right ? How can I do that ?
Thanks for answer.
Setting a cookie could work. A slightly better/broader solution would be to use LocalStorage
. This way, the change would appear in any web browser. There is a good example for using LocalStorage if you are new to this on W3Schools: https://www.w3schools.com/html/html5_webstorage.asp
From my code, I have
if (typeof Storage !== 'undefined') {
if (localStorage) localStorage.setItem('bodyclass', color);
}
and
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");
}
No need to use cookies (cookies are useful for servers, not for browsers). Use localStorage to save the current background color locally.
<!-- page1.html -->
<script>
document.styleSheets[0].cssRules[0].style.backgroundColor="white";
localStorage.backgroundColor = "white";
</script>
In page2.html you must get the property from localStorage and set the background with it.
<!-- 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;")
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.