【问题标题】:How to toggle many css styles to make a dark mode?如何切换多种 CSS 样式以制作暗模式?
【发布时间】:2022-10-25 00:01:56
【问题描述】:

我正在使用 HTML、CSS 和 JavaScript 来构建我的网站。我想添加一个暗模式切换按钮,因此通过单击,它将切换到暗/亮模式,但我的 JavaScript 脚本仅适用于CSS 样式 - body。但实际上,我有很多div,它们很轻,但它们并没有改变颜色。

这是我的 HTML 代码(带有 JS <script> 容器):

我该如何解决这个问题,所以通过点击按钮我可以让我的网站进入黑暗模式?

function darkMode() {
  var element = document.body
  element.classList.toggle("dark-mode");
  element.classList.toggle("yeaaaaaa");
}
body {
  font-family: 'Montserrat', sans-serif;
  background-color: #fff;
}

.dark_mode {
  background-color: #000;
}

.yeaaaaaa {
  background-color: #111;
}


/* main styles */

.main {
  display: grid;
  background-color: #f5f7fa;
  grid-template-columns: 22.15em auto;
  grid-template-rows: auto auto;
}

.grid-item {
  background: #1e2939;
}

.photo-coverup {
  display: flex;
  align-items: flex-end;
}

.info-name {
  color: #1e2939;
  margin-bottom: 5px;
}

.info-list {
  color: #1e2939;
  margin-bottom: 25px;
}

.info-yee {
  color: #1e2939;
  width: 400px;
}


/* about styles */

.about {
  background-color: #F1F9fc;
  padding: 15px 120px 10px 50px;
}

.info {
  color: #1e2939;
}

.texx-alt {
  font-style: normal;
  color: black;
}

#delegar {
  position: fixed;
  right: 10px;
  top: 10px;
  width: 90px;
  height: 35px;
  border: none;
  outline: none;
  color: #87c9f5;
  background: #1e2939;
  cursor: pointer;
  z-index: 0;
  border-radius: 15px 0 0 15px;
  -webkit-transition: ease-in 1s;
  transition: color 1s;
}

#delegar:hover {
  color: #1e2939;
  background-color: #87c9f5;
  font-weight: bold;
}
<!--Main-->
<div class="main grid">
  <div class="photo-coverup grid-item">
    <img src="img/Profile pic.jpg" alt="Dude Pic" class="photo">
  </div>
  <!--About User-->
  <span>
        <div class="about grid-item yeaaaaaa">
          <p class="info">
          <h2 class="info">Developer and Graphic Designer</h2>
          <h1 class="info-name">George Mos</h1>
          <p class="info-yee">
            My name is George (GMos) Mos. I'm a graphic designer and programmer. I have:
          </p>
          <ul class="info-list">
            <li class="info-section-list-component">4-year-experience in Adobe Photoshop and Adobe Illustrator</li>
            <li class="info-section-list-component">3-year-experience in programming
              (Python, HTML5, Bash and JavaScript)</li>
          </ul>
          <p class="info">I'm from Ukraine, Kyiv. I work as a freelancer and, usually, my work consists
            of creating logos, wallpapers, art and/
            or making softwares, programs and websites. My life motto: "Optimistic and ambitious"
          </p>
          <p class="info">In my spare time I often lay back in Discord either texting or taking part in a voice
            channels. If you wanna join, don't hesitate yourself by following the "Discord" link in "Social Media"
            section! (or you can just <a href="https://discord.gg/PGkJgQtCwZ" class="texx-alt">click here</a> though)
          </p>
          </p>
        </div>
      </span>
  <div>
    <button onclick="darkMode()" id="delegar">Dark Mode</button>
  </div>

【问题讨论】:

    标签: javascript html css darkmode


    【解决方案1】:

    只需使用 JavaScript 将 dark-mode 类添加到您的 body 标记中,然后在它们前面使用 .dark-mode 定义所有深色样式,如下所示:

    a {
        color: #330033; /* or whatever dark color */
    }
    
    .dark-mode a {
        color: white; /* or whatever light color */
    }
    

    有关 CSS 特异性和级联的更多信息,请参阅此页面:

    https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

    我建议将所有暗模式样式与它们上方的注释组合在一起,例如 /* Dark mode styles: */,并将它们放在样式表的底部(在任何响应断点之上),这样它们就在一起了,它们是您的常规样式 - 因为 CSS 采用最后定义的样式(因此,级联)。这样您就不会遇到重新定义样式的问题。确保所有覆盖样式都有更多的比他们试图覆盖的特异性。尽可能避免使用!important

    【讨论】:

    • 你好!感谢您的答复!但是,不幸的是,我不是 HTML 和 CSS 方面的专业人士,所以请您确定一下,“使用 JavaScript 将类暗模式添加到您的 body 标签中,然后使用 .dark 定义您的所有暗样式-”是什么意思?他们面前的模式”?
    • 您已经在上面的代码中将该类添加到正文中。只需使用.darkmode 将新样式添加到您的 CSS 样式表,然后是空格,然后是要更改颜色的选择器。
    【解决方案2】:

    我会使用 CSS 变量 (w3schools)。您可以在 :root 中创建一些变量,例如明亮的背景或文本颜色,然后将它们分配给不同的元素。如果要更改为暗模式,只需相应地更改变量(文本为亮色,背景为暗色):

    :root {
        --text: #1e2939;
        --bg: #F1F9fc;
    }
    
    body {
        font-family: 'Montserrat', sans-serif;
        background-color: #fff;
    }
    
    .yeaaaaaa {
      background-color: #111;
    }
      
      /* main styles */
      .main {
        display: grid;
        background-color: #f5f7fa;
        grid-template-columns: 22.15em auto;
        grid-template-rows: auto auto;
      }
      
      .grid-item {
        background: #1e2939;
      }
      
      .photo-coverup {
        display: flex;
        align-items: flex-end;
      }
    
      .info-name {
        color: var(--text);
        margin-bottom: 5px;
      }
      
      .info-list {
        color: var(--text);
        margin-bottom: 25px;
      }
      
      .info-yee {
        color: var(--text);
        width: 400px;
      }
    
      /* about styles */
      .about {
        background-color: var(--bg);
        padding: 15px 120px 10px 50px;
      }
    
    .info {
        color: var(--text);
      }
    
    .texx-alt {
        font-style: normal;
        color: black;
    }
    
    #delegar {
        position:fixed;
        right: 10px;
        top: 10px;
        width: 90px;
        height: 35px;
        border: none;
        outline: none;
        color: #87c9f5;
        background: var(--text);
        cursor: pointer;
        z-index: 0;
        border-radius: 15px 0 0 15px;
        -webkit-transition: ease-in 1s;
        transition: color 1s;
    }
    
    #delegar:hover {
      color: #1e2939;
      background-color: #87c9f5;
      font-weight: bold;
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
    
      </head>
    
      <body>
        <!--Main-->
        <div class="main grid">
          <div class="photo-coverup grid-item">
            <img src="img/Profile pic.jpg" alt="Dude Pic" class="photo">
          </div>
          <!--About User-->
          <span>
            <div class="about grid-item yeaaaaaa">
              <p class="info">
              <h2 class="info">Developer and Graphic Designer</h2>
              <h1 class="info-name">George Mos</h1>
              <p class="info-yee">
                My name is George (GMos) Mos. I'm a graphic designer and programmer. I have:
              </p>
              <ul class="info-list">
                <li class="info-section-list-component">4-year-experience in Adobe Photoshop and Adobe Illustrator</li>
                <li class="info-section-list-component">3-year-experience in programming
                  (Python, HTML5, Bash and JavaScript)</li>
              </ul>
              <p class="info">I'm from Ukraine, Kyiv. I work as a freelancer and, usually, my work consists
                of creating logos, wallpapers, art and/
                or making softwares, programs and websites. My life motto: "Optimistic and ambitious"
              </p>
              <p class="info">In my spare time I often lay back in Discord either texting or taking part in a voice
                channels. If you wanna join, don't hesitate yourself by following the "Discord" link in "Social Media"
                section! (or you can just <a href="https://discord.gg/PGkJgQtCwZ" class="texx-alt">click here</a> though)
              </p>
              </p>
            </div>
          </span>
        <div>
          <button id="delegar">Dark Mode</button>
        </div>
        <script>
            const button = document.getElementById('delegar');
            button.addEventListener('click', (event) => {
                if (button.innerHTML === "Dark Mode") {
                    document.documentElement.style.setProperty('--text', '#eee');
                    document.documentElement.style.setProperty('--bg', '#1e2939');
                    button.innerHTML = "Light Mode";
                } else {
                    document.documentElement.style.setProperty('--text', '#1e2939');
                    document.documentElement.style.setProperty('--bg', '#F1F9fc');
                    button.innerHTML = "Dark Mode";
                }
            });
        </script>
      </body>
    </html>

    【讨论】:

    • 很酷!干杯!
    【解决方案3】:

    虽然 Sean Kendle 的方法可以工作,但如果您不需要担心旧版浏览器,还有其他选项可能更简洁且实施起来更省力。我在下面提供一些想法供您考虑。 CSS 变量是最重要的一个。

    SCSS

    为了简化在 css 中的工作,您可以考虑使用scss

    使用 scss 而不是使用 .dark-mode 作为所有深色样式的开头,您可以将所有深色模式样式嵌套在一个深色模式定义中。例如:

    .dark-mode{
    
        background-color: black;
    
        a{
            color: white;
        }
    
        //any other dark styles
    
    }
    

    用户偏好媒体查询

    为了进一步改进,考虑到操作系统通常允许人们在系统级别指定暗模式偏好,我们现在有一个得到很好支持的media query in CSS to detect that OS preference

    @media (prefers-color-scheme: dark) {
    
     //dark styles here.
    
    }
    

    Jason Pamental has an interesting article here 使用更喜欢黑暗媒体查询,除了用户在网站本身上切换,并使用 css 变量以简单而强大的方式切换样式。有a demo of the concept here.

    CSS 变量

    如果您能够使用 css 变量,您可以只定义 css 一次,然后简单地翻转变量以切换到暗模式。这是上述演示中 css 的简化版本,用于说明如何使用变量更改暗模式的颜色:

    :root {
    
      --color-dark: #3a3a3a;
      --color-light: #eee;
      
      --color-text: var(--color-dark);
      --color-background: var(--color-light);
      
    }
    
    body {
      background-color: var(--color-background);
      color: var(--color-text);
      transition: background-color 0.25s ease, color 0.25s ease;
    }
    
    
    .dark-mode {
      /* flip the light and dark variables */
      --color-text: var(--color-light);
      --color-background: var(--color-dark);
    }
    

    【讨论】:

    • 是的,这是改进我的答案的一种更好、更先进的方法。干杯!
    【解决方案4】:

    只是为了向您展示一个工作示例,您可以使用 prefers-color-scheme 进行自动切换,还可以创建暗模式和亮模式类,用于手动切换。

    document.getElementById("theme").addEventListener("click", () => {
      const meta = document.querySelector('meta[name="color-scheme"]');
      if (meta.content === "light") {
        meta.content = "dark";
        document.body.classList.remove("light-mode");
        document.body.classList.add("dark-mode");
      } else {
        meta.content = "light";
        document.body.classList.remove("dark-mode");
        document.body.classList.add("light-mode");
      }
    });
    @media (prefers-color-scheme: dark) {
        :root {
            --color-primary: #0a0a0a;
            --color-secondary: #339eff;
        }
    }
    
    @media (prefers-color-scheme: light) {
        :root {
            --color-primary: #ffffff;
            --color-secondary: #ff7e33;
        }
    }
    
    .light-mode {
        --color-primary: #ffffff;
        --color-secondary: #ff7e33;
    }
    
    .dark-mode {
        --color-primary: #0a0a0a;
        --color-secondary: #339eff;
    }
    
    body {
        background-color: var(--color-primary);
        color: var(--color-secondary);
    }
    <!DOCTYPE html>
    <html lang="pt-BR" xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br">
      <head>
        <meta name="color-scheme" content="dark light" />
        <meta name="theme-color" media="(prefers-color-scheme: dark)" />
        <meta name="theme-color" media="(prefers-color-scheme: light)" />
      </head>
      <body>
        This is a test
    
        <button id="theme">Change theme</button>
      </body>
    </html>

    您可以根据需要更改它,但这是根据 web.dev 的。请记住设置首选颜色方案颜色,然后使用 .light-mode 和 .dark-mode 类自动或通过手动切换更改它。

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2020-05-27
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 2022-01-10
      相关资源
      最近更新 更多