最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to enable Dark Mode in all pages? - Stack Overflow

programmeradmin1浏览0评论

So I have a JS script and when a user presses the button that says Dark Mode the page switches to dark_theme.css (instead of using theme.css which is the Ligh Mode css) and when the user presses Light Mode button it switches back to theme.css. So my problem is that when a user uses darm_theme.css and loads a different page or refreshes the current page the theme switches back to light mode. How can I somehow save the user's selection/choice?

function swapStyleSheet(sheet){
    document.getElementById('theme').setAttribute('href', sheet);
}
I have one file called theme.css and one more called dark_theme.css
<link id="theme" rel="stylesheet" type="text/css" href="theme.css">
...more html here...
<p><button class="colormode" onclick="swapStyleSheet('dark_theme.css')">Dark Mode</button> <button class="colormode" onclick="swapStyleSheet('theme.css')">Light Mode</button></p>

So I have a JS script and when a user presses the button that says Dark Mode the page switches to dark_theme.css (instead of using theme.css which is the Ligh Mode css) and when the user presses Light Mode button it switches back to theme.css. So my problem is that when a user uses darm_theme.css and loads a different page or refreshes the current page the theme switches back to light mode. How can I somehow save the user's selection/choice?

function swapStyleSheet(sheet){
    document.getElementById('theme').setAttribute('href', sheet);
}
I have one file called theme.css and one more called dark_theme.css
<link id="theme" rel="stylesheet" type="text/css" href="theme.css">
...more html here...
<p><button class="colormode" onclick="swapStyleSheet('dark_theme.css')">Dark Mode</button> <button class="colormode" onclick="swapStyleSheet('theme.css')">Light Mode</button></p>

Share Improve this question asked Oct 21, 2017 at 21:24 ApostApost 391 silver badge8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Use localStorage for that:

function swapStyleSheet(sheet){
  document.getElementById('theme').setAttribute('href', sheet);
  localStorage.setItem("sheet", sheet);
}

window.onload = _ =>
 swapStyleSheet(
  localStorage.getItem("sheet") || "default.css"
 );

You can use cookies. (Cookie functions here: https://stackoverflow./a/24103596)

function swapStyleSheet(sheet){
    document.getElementById('theme').setAttribute('href', sheet);
    createCookie ("sheet", sheet);
}
document.addEventListener("DOMContentLoaded", function(event) { 
    var item = readCookie ("sheet") || "default.css";
    swapStyleSheet (item);
});
发布评论

评论列表(0)

  1. 暂无评论