简体   繁体   English

如何使用JavaScript永久更改网站中的CSS文件?

[英]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>

You can do this with the Web Storage API . 您可以使用Web Storage API进行此操作

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.

相关问题 如何永久更改CSS文件,以便将更改保存在服务器上的实际文件中? - How can I change a CSS file permanently so the changes are saved in the actual file on the server? 我怎么知道用户是否篡改了CSS或JavaScript来改变我网站的外观? - How can I know if the user tampered with the CSS or JavaScript to change the appearance of my website? 如何永久更改对象的样式? - How can I permanently change the style of my object? 如何更改此 javascript 动画在我网站上的位置? - How can i change the placement of this javascript animation on my website? 如何使用nodejs获取网站上所有图像/ css / js的所有文件大小? - How can I get all the file sizes of all the images/css/js on my website using nodejs? 如何使用JavaScript永久修改单独文件上的JSON对象? - How can I permanently modify a JSON object on a separate file with JavaScript? 如何使用JavaScript计算网站访问者的数量? - How can I count the number of the visitors on my website using JavaScript? 我无法使用 javascript 永久更改简单 html 页面的背景颜色 - I can't change permanently the background color of a simple html page using javascript 如何根据URL的结果在我的angular 7网站上更改css元素? - How can I change a css element on my angular 7 website based on result for a url? 是否可以仅使用JavaScript和按钮元素来更改整个网站(两页)上的所有图片? - Can I change all the pictures on my entire website (2 pages), using just JavaScript and a button element?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM