create switch for changing theme intead of browser page style html

丶灬走出姿态 提交于 2020-01-06 07:10:26

问题


I added a theme in my HTML page by:

<link rel="alternate stylesheet" href="css/dark.css" title="dark">

this creates an option to switch theme from view>style in browser as it is expected to. I want to create a switch in the page itself for changing the theme. <button>Switch Theme</button>will create a button but how do I make it switch theme?


回答1:


You should trigger a change in the href attribute of the <link> tag on the click of the button, as demonstrated:

HTML

<link rel="stylesheet" href="dark.css" id="theme">
<button id="switch">Switch Theme</button>

JavaScript

document.getElementById('switch').onclick = function() {
  if (document.getElementById('theme').href == "dark.css") {
    document.getElementById('theme').href = "light.css";
  } else {
    document.getElementById('theme').href = "dark.css";
  }
};

Now, the dark.css and light.css would contain different styles for your elements for both the themes respectively. For example:

dark.css

body{
    background: #000;
}

light.css

body{
    background: #fff;
}



回答2:


this is very simple you need to bind the click to function and call it:

Replacing css file on the fly (and apply the new style to the page)



来源:https://stackoverflow.com/questions/48241165/create-switch-for-changing-theme-intead-of-browser-page-style-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!