[英]How can I permanently change css file in my website using javascript?
I am trying to add a light/dark style function to my website. 我正在尝试向我的网站添加浅色/深色样式功能。 I wrote a code to change between two stylesheets when a button is clicked but whenever I go to a different route the style goes back to the regular one. 我编写了一个代码,当单击一个按钮时,可以在两个样式表之间进行切换,但是每当我转到其他路线时,样式就会恢复为常规样式。
Javascript: Javascript:
function swapStyleSheet(sheet){
document.getElementById('pageStyle').setAttribute('href', sheet);
}
HTML: HTML:
<link rel="stylesheet" href="/stylesheets/light.css" id="pageStyle">
<body>
<li><a id="navLinks" onclick="swapStyleSheet('/stylesheets/light.css')">Light Style!</a></li>
<li><a id="navLinks" onclick="swapStyleSheet('/stylesheets/main.css')">Dark Style!</a></li>
</body>
This is similar to using cookies, but the data is stored in the browser rather than on the server. 这类似于使用cookie,但是数据存储在浏览器中而不是服务器中。 Supported by all modern browsers. 所有现代浏览器均支持。
JS: JS:
function swapStyleSheet(sheet){
document.getElementById('pageStyle').setAttribute('href', sheet);
window.localStorage.setItem("pageStyle", sheet);
}
window.onload = function() {
swapStyleSheet(window.localStorage.getItem("pageStyle"));
}
HTML: HTML:
<li><a id="navLinks" onclick="swapStyleSheet('/stylesheets/light.css')">Light Style!</a></li>
<li><a id="navLinks" onclick="swapStyleSheet('/stylesheets/main.css')">Dark Style!</a></li>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.