如何使用 CSS 和 JavaScript 制作可更改的主题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8796107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:32:32  来源:igfitidea点击:

How to make changeable themes using CSS and JavaScript

javascriptcssthemes

提问by user1130772

I'm pretty new to CSS and JavaScript and I was wondering if you could make a script that allows you to change what stylesheet the site uses.

我对 CSS 和 JavaScript 还很陌生,我想知道您是否可以制作一个脚本来更改站点使用的样式表。

Say: you had a green theme where everything is shades of green. What would you do so the user can change it to red with the press of a button?

说:你有一个绿色主题,所有东西都是绿色的。你会怎么做,让用户可以通过按下按钮将其更改为红色?

Has anyone any idea how to do this?

有谁知道如何做到这一点?

回答by Selvakumar Arumugam

You can set an Id to the link tag and switch the css at runtime.

您可以为链接标签设置一个 Id 并在运行时切换 css。

HTML

HTML

<link type="text/css" rel="stylesheet" media="all" href="../green.css" id="theme_css" />

JS

JS

document.getElementById('buttonID').onclick = function () { 
    document.getElementById('theme_css').href = '../red.css';
};

回答by Nisarg

You could use CSS Variables(also known as Custom Properties) for such changes, given that they are supported by all modern browsers.

您可以使用CSS 变量(也称为自定义属性)进行此类更改,因为所有现代浏览器支持它们。



So, let's say you have a green/white theme, where green being the primary color, and white complementing it. The site might look like the following:

因此,假设您有一个绿色/白色主题,其中绿色是主要颜色,白色是它的补充。该网站可能如下所示:

How the site looks

网站的外观

body {
  font-family: "Segoe UI", "Serif", "Verdana", "Arial";
}

.container {
  display: grid;
  grid-template-columns: 120px 1fr;
  grid-template-rows: 50px 1fr 30px;
  grid-gap: 5px;
}

.header {
  grid-row: 1;
  grid-column: 1 / 3;
  background-color: #ddd;
}

.nav {
  grid-column: 1;
  grid-row: 2;
  border-right: 1px solid green;
}

.content {
  grid-column: 2;
  grid-row: 2;
  padding: 10px;
}

.footer {
  grid-row: 3;
  grid-column: 1 / 3;
  text-align: center;
}


/* Child items. */

.header-logo {
  float: left;
  width: 100px;
  background-color: green;
  height: 50px;
  color: white;
  font-size: 30px;
  padding: 3px 5px;
  box-sizing: border-box;
}

.nav-links {
  list-style: none;
  margin: 5px 0 0 0;
  padding: 0;
}

.nav-links--link {
  color: green;
  background-color: white;
  width: 100%;
  height: 30px;
  margin: 0 0 5px 0;
  padding: 4px 5px;
  box-sizing: border-box;
  cursor: pointer;
}

.nav-links--link.active,
.nav-links--link:hover {
  background-color: green;
  color: white;
}

.footer-note {
  color: green;
  background-color: white;
  padding: 3px 0;
  display: block;
}
<div class="container">
  <div class="header">
    <div class="header-logo">
      LOGO
    </div>
  </div>

  <div class="nav">
    <ul class="nav-links">
      <li class="nav-links--link active">
        Home
      </li>
      <li class="nav-links--link">
        About
      </li>
      <li class="nav-links--link">
        Contact Us
      </li>
    </ul>
  </div>

  <div class="content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta, ea.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis id tenetur repudiandae deserunt, ipsam quisquam dicta tempora. Temporibus, vel, veritatis.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur dignissimos odio id repellat quam, assumenda magnam! Beatae perferendis error exercitationem molestias explicabo earum ipsam maiores ullam natus dolorum, dolorem itaque reiciendis
      nihil placeat incidunt aperiam tempora, commodi eveniet. Minima iusto porro iste quae dignissimos neque dolor adipisci non, soluta nisi!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates, dolorem blanditiis exercitationem excepturi, impedit iure.</p>
  </div>

  <div class="footer">
    <span class="footer-note">
          Lorem ipsum dolor sit amet.
        </span>
  </div>
</div>



So the first step to move to CSS Variables would be to refactorout the theme colors into variables --primary-colorand --secondary-color. Here's how your stylesheet looks after the change.

因此,迁移到 CSS 变量的第一步是将主题颜色重构为变量--primary-color--secondary-color. 以下是更改后样式表的外观。

You could begin by setting the default theme colors into the :rootelement style declaration:

您可以首先将默认主题颜色设置到:root元素样式声明中:

:root {
    --primary-color: green;
    --secondary-color: white;
}

Then, you can replace all instances of hardcoded"green" in the stylesheet with a call to the primary color variable: var(--primary-color). So the styles for your logo might look like the following:

然后,您可以替换的所有实例硬编码一起原色变量来电样式表“绿色”: var(--primary-color)。因此,您的徽标样式可能如下所示:

.header-logo {
  ...
  background-color: var(--primary-color);
  color: var(--secondary-color);
  ...
}

:root {
  --primary-color: green;
  --secondary-color: white;
}

body {
  font-family: "Segoe UI", "Serif", "Verdana", "Arial";
}

.container {
  display: grid;
  grid-template-columns: 120px 1fr;
  grid-template-rows: 50px 1fr 30px;
  grid-gap: 5px;
}

.header {
  grid-row: 1;
  grid-column: 1 / 3;
  background-color: #ddd;
}

.nav {
  grid-column: 1;
  grid-row: 2;
  border-right: 1px solid var(--primary-color);
}

.content {
  grid-column: 2;
  grid-row: 2;
  padding: 10px;
}

.footer {
  grid-row: 3;
  grid-column: 1 / 3;
  text-align: center;
}


/* Child items. */

.header-logo {
  float: left;
  width: 100px;
  background-color: var(--primary-color);
  height: 50px;
  color: var(--secondary-color);
  font-size: 30px;
  padding: 3px 5px;
  box-sizing: border-box;
}

.nav-links {
  list-style: none;
  margin: 5px 0 0 0;
  padding: 0;
}

.nav-links--link {
  color: var(--primary-color);
  background-color: var(--secondary-color);
  width: 100%;
  height: 30px;
  margin: 0 0 5px 0;
  padding: 4px 5px;
  box-sizing: border-box;
  cursor: pointer;
}

.nav-links--link.active,
.nav-links--link:hover {
  background-color: var(--primary-color);
  color: var(--secondary-color);
}

.footer-note {
  color: var(--primary-color);
  background-color: var(--secondary-color);
  padding: 3px 0;
  display: block;
}
<div class="container">
  <div class="header">
    <div class="header-logo">
      LOGO
    </div>
  </div>

  <div class="nav">
    <ul class="nav-links">
      <li class="nav-links--link active">
        Home
      </li>
      <li class="nav-links--link">
        About
      </li>
      <li class="nav-links--link">
        Contact Us
      </li>
    </ul>
  </div>

  <div class="content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta, ea.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis id tenetur repudiandae deserunt, ipsam quisquam dicta tempora. Temporibus, vel, veritatis.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur dignissimos odio id repellat quam, assumenda magnam! Beatae perferendis error exercitationem molestias explicabo earum ipsam maiores ullam natus dolorum, dolorem itaque reiciendis
      nihil placeat incidunt aperiam tempora, commodi eveniet. Minima iusto porro iste quae dignissimos neque dolor adipisci non, soluta nisi!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates, dolorem blanditiis exercitationem excepturi, impedit iure.</p>
  </div>

  <div class="footer">
    <span class="footer-note">
          Lorem ipsum dolor sit amet.
        </span>
  </div>
</div>



Now, if you intend to change the color from "green" to "red", all you need to do is change the value of --primary-colorto "red". And, you can do that using Javascript!

现在,如果您打算将颜色从“绿色”更改为“红色”,您需要做的就是将 的值更改--primary-color为“红色”。而且,您可以使用 Javascript 做到这一点!

With plain JS, you can set the color to red using:

使用纯 JS,您可以使用以下方法将颜色设置为红色:

document.body.style.setProperty("--primary-color", "red");

Or, with jQuery you could do:

或者,使用 jQuery,您可以执行以下操作:

$(document.body).css("--primary-color", "red");

$(document.body).css("--primary-color", "red");
:root {
  --primary-color: green;
  --secondary-color: white;
}

body {
  font-family: "Segoe UI", "Serif", "Verdana", "Arial";
}

.container {
  display: grid;
  grid-template-columns: 120px 1fr;
  grid-template-rows: 50px 1fr 30px;
  grid-gap: 5px;
}

.header {
  grid-row: 1;
  grid-column: 1 / 3;
  background-color: #ddd;
}

.nav {
  grid-column: 1;
  grid-row: 2;
  border-right: 1px solid var(--primary-color);
}

.content {
  grid-column: 2;
  grid-row: 2;
  padding: 10px;
}

.footer {
  grid-row: 3;
  grid-column: 1 / 3;
  text-align: center;
}


/* Child items. */

.header-logo {
  float: left;
  width: 100px;
  background-color: var(--primary-color);
  height: 50px;
  color: var(--secondary-color);
  font-size: 30px;
  padding: 3px 5px;
  box-sizing: border-box;
}

.nav-links {
  list-style: none;
  margin: 5px 0 0 0;
  padding: 0;
}

.nav-links--link {
  color: var(--primary-color);
  background-color: var(--secondary-color);
  width: 100%;
  height: 30px;
  margin: 0 0 5px 0;
  padding: 4px 5px;
  box-sizing: border-box;
  cursor: pointer;
}

.nav-links--link.active,
.nav-links--link:hover {
  background-color: var(--primary-color);
  color: var(--secondary-color);
}

.footer-note {
  color: var(--primary-color);
  background-color: var(--secondary-color);
  padding: 3px 0;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="header">
    <div class="header-logo">
      LOGO
    </div>
  </div>

  <div class="nav">
    <ul class="nav-links">
      <li class="nav-links--link active">
        Home
      </li>
      <li class="nav-links--link">
        About
      </li>
      <li class="nav-links--link">
        Contact Us
      </li>
    </ul>
  </div>

  <div class="content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta, ea.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis id tenetur repudiandae deserunt, ipsam quisquam dicta tempora. Temporibus, vel, veritatis.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur dignissimos odio id repellat quam, assumenda magnam! Beatae perferendis error exercitationem molestias explicabo earum ipsam maiores ullam natus dolorum, dolorem itaque reiciendis
      nihil placeat incidunt aperiam tempora, commodi eveniet. Minima iusto porro iste quae dignissimos neque dolor adipisci non, soluta nisi!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates, dolorem blanditiis exercitationem excepturi, impedit iure.</p>
  </div>

  <div class="footer">
    <span class="footer-note">
          Lorem ipsum dolor sit amet.
        </span>
  </div>
</div>



I went one step further and created some buttons to show how you could allow the user to choose a set of theme colors - and change the values CSS Variables using jQuery.

我更进一步,创建了一些按钮来展示如何允许用户选择一组主题颜色 - 并使用 jQuery 更改 CSS 变量的值。

Here's how the snippet below looks on Chrome 64 - in case you are still using a browser that doesn't support CSS Variables:

以下是 Chrome 64 上的代码片段 - 如果您仍在使用不支持 CSS 变量的浏览器:

Theme changer

主题转换器

$(".header--theme-button").on("click", function() {
  var primaryColor = $(this).css("--theme-primary");
  var secondaryColor = $(this).css("--theme-secondary");

  $(".header--theme-button").removeClass("active");
  $(this).addClass("active");

  $(document.body).css("--primary-color", primaryColor);
  $(document.body).css("--secondary-color", secondaryColor);
});
:root {
  --primary-color: orange;
  --secondary-color: white;
  --theme-primary: black;
  --theme-secondary: white;
}

body {
  font-family: "Segoe UI", "Serif", "Verdana", "Arial";
}

.container {
  display: grid;
  grid-template-columns: 120px 1fr;
  grid-template-rows: 50px 1fr 30px;
  grid-gap: 5px;
}

.header {
  grid-row: 1;
  grid-column: 1 / 3;
}

.nav {
  grid-column: 1;
  grid-row: 2;
  border-right: 1px solid var(--primary-color);
}

.content {
  grid-column: 2;
  grid-row: 2;
  padding: 10px;
}

.footer {
  grid-row: 3;
  grid-column: 1 / 3;
  text-align: center;
}


/* Child items. */

.header-logo {
  float: left;
  width: 100px;
  background-color: var(--primary-color);
  height: 50px;
  color: var(--secondary-color);
  font-size: 30px;
  padding: 3px 5px;
  box-sizing: border-box;
}

.header-settings {
  float: right;
  height: 50px;
}

.nav-links {
  list-style: none;
  margin: 5px 0 0 0;
  padding: 0;
}

.nav-links--link {
  color: var(--primary-color);
  background-color: var(--secondary-color);
  width: 100%;
  height: 30px;
  margin: 0 0 5px 0;
  padding: 4px 5px;
  box-sizing: border-box;
  cursor: pointer;
}

.nav-links--link.active,
.nav-links--link:hover {
  background-color: var(--primary-color);
  color: var(--secondary-color);
}

.footer-note {
  color: var(--primary-color);
  background-color: var(--secondary-color);
  padding: 3px 0;
  display: block;
}

.header--theme-button {
  height: 30px;
  width: 30px;
  margin: 10px 5px 0 0;
  display: inline-block;
  border-top: 15px solid var(--theme-primary);
  border-bottom: 15px solid var(--theme-secondary);
  border-right: 0;
  border-left: 0;
  padding: 0;
  box-shadow: 0 0 3px gray;
}

.header--theme-button:hover {
  box-shadow: 2px 2px 2px gray;
}

.header--theme-button.active {
  box-shadow: 3px 3px 3px gray;
}
<div class="container">
  <div class="header">
    <div class="header-logo">
      LOGO
    </div>
    <div class="header-settings">
      <button type="button" class="header--theme-button active" style="--theme-primary:orange; --theme-secondary:white;">
          </button>
      <button type="button" class="header--theme-button" style="--theme-primary:#2196F3; --theme-secondary:#eee;">
          </button>
      <button type="button" class="header--theme-button" style="--theme-primary:purple; --theme-secondary:white;">
          </button>
      <button type="button" class="header--theme-button" style="--theme-primary:#F44336; --theme-secondary:white;">
          </button>
      <button type="button" class="header--theme-button" style="--theme-primary:green; --theme-secondary:white;">
          </button>
      <button type="button" class="header--theme-button" style="--theme-primary:#FFEB3B; --theme-secondary:#222;">
          </button>
    </div>
  </div>

  <div class="nav">
    <ul class="nav-links">
      <li class="nav-links--link active">
        Home
      </li>
      <li class="nav-links--link">
        About
      </li>
      <li class="nav-links--link">
        Contact Us
      </li>
    </ul>
  </div>

  <div class="content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta, ea.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis id tenetur repudiandae deserunt, ipsam quisquam dicta tempora. Temporibus, vel, veritatis.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequuntur dignissimos odio id repellat quam, assumenda magnam! Beatae perferendis error exercitationem molestias explicabo earum ipsam maiores ullam natus dolorum, dolorem itaque reiciendis
      nihil placeat incidunt aperiam tempora, commodi eveniet. Minima iusto porro iste quae dignissimos neque dolor adipisci non, soluta nisi!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates, dolorem blanditiis exercitationem excepturi, impedit iure.</p>
  </div>

  <div class="footer">
    <span class="footer-note">
          Lorem ipsum dolor sit amet.
        </span>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

回答by Jeremy Harris

Yes, you can change CSS with Javascript. See this tutorialfor more info. It basically links multiple stylesheets like this:

是的,您可以使用 Javascript 更改 CSS。有关更多信息,请参阅本教程。它基本上像这样链接多个样式表:

<link rel="stylesheet" type="text/css" title="blue"
   href="http://example.com/css/blue.css">
<link rel="alternate stylesheet" type="text/css" title="pink"
   href="http://example.com/css/pink.css">

And then uses Javascript to change it:

然后使用 Javascript 对其进行更改:

<form>
<input type="submit" onclick="switch_style('blue');return false;" name="theme" value="Blue Theme" id="blue">
<input type="submit" onclick="switch_style('pink');return false;" name="theme" value="Pink Theme" id="pink">
</form>

The switch_style() function is written in that tutorial.

switch_style() 函数是在该教程中编写的。

回答by kd44

If you want to switch back and forth between themes I recommend using the following for your javascript:

如果您想在主题之间来回切换,我建议对您的 javascript 使用以下内容:

var count = 0

document.getElementById('trigger').onclick = function () {
    count = count + 1;
    if (count%2!=0){
      document.getElementById('default').href = 'changeTheme.css';
    } else {
      document.getElementById('default').href = 'main.css';
    }
};

Then using the markup mentioned earlier

然后使用前面提到的标记

回答by Stefan Avramovic

Or just put your theme css in a css file and pass it to the function, On page load the if (localStorage.getItem("theme") != "") checks if theme has been set.. Here you have an example:

或者只是将您的主题 css 放在一个 css 文件中并将其传递给函数,在页面加载 if (localStorage.getItem("theme") != "") 检查主题是否已设置.. 这里有一个示例:

   if (localStorage.getItem("theme") != "") {
        loadcssfile(localStorage.getItem("theme"));
      }

      function loadcssfile(filename) {
        if (filename != "") {
          localStorage.setItem("theme", filename);
        }
        
        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);

        if (typeof fileref != "undefined")
          document.getElementsByTagName("head")[0].appendChild(fileref);
      }
   <div onclick="loadcssfile('css/pink.css')" id="pink">
      Pink
    </div>
    <div
      onclick="loadcssfile('css/blue.css')" id="blue">
      Blue
    </div>

回答by Boiethios

You don't even need any Javascript:

你甚至不需要任何 Javascript:

input[type=radio][value=light]:checked ~ article {
    color: #222;
    background-color: #FFEEAA;
}

input[type=radio][value=dark]:checked ~ article {
    color: #EEE;
    background-color: grey;
}
<body>
  <input type="radio" name="theme" value="light" checked="checked">Light<br>
  <input type="radio" name="theme" value="dark">Dark<br>
  <article>
    <h1>My super page!</h1>
    <p>
      Quibusdam sit repudiandae consequuntur doloremque illum ut ex quo. Esse temporibus est id suscipit repellat. Distinctio voluptatem voluptates asperiores dolorem dolorem placeat corporis quae. Quaerat voluptatem magni dignissimos rerum distinctio odio id.
    </p>
  </article>
</body>