如何在使用 CSS 為網站建立深色/淺色模式


透過更改頁面的文字顏色和背景顏色,我們可以為我們的網站新增深色/淺色模式。

語法

可以使用以下語法來應用深色模式。

Selector {
   color: white;
   background-color: black
}

示例

 實際演示

<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            font-size: 1.4em;
            text-align: center;
         }
         .dark {
            color: white;
            background-color: black;
         }
      </style>
   </head>
   <body>
      <div>
         <p>Suspendisse eget finibus nulla, a pulvinar est. Suspendisse eget eleifend nibh. In nec massa molestie, vehicula sapien a, consectetur nunc. Aenean at nisl vulputate mi scelerisque commodo nec et mauris. Duis tincidunt auctor posuere.</p>
         <button id="btn" onclick="change()">Normal Mode</button>
      </div>
      <script>
         let btnText = document.getElementById("btn");
         function change() {
            let btn = document.body;
            btn.classList.toggle("dark");
            if (btnText.innerHTML === "Normal Mode") {
               btnText.innerHTML = "Dark Mode!";
            } else {
               btnText.innerHTML = "Normal Mode";
            }}
      </script>
   </body>
</html>

本例輸出如下

示例

 實際演示

<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            font-size: 1.4em;
            text-align: center;
         }
         .dark {
            color: white;
            background-color: black;
         }
      </style>
   </head>
   <body>
      <div>
         <button id="btn" onclick="change()">Normal Mode</button>
         <p>Duis tincidunt auctor posuere.</p>
         <img src="https://images.unsplash.com/photo-1610718055968-4e3cf23d96db?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=200" />
      </div>
      <script>
         let btnText = document.getElementById("btn");
         function change() {
            let btn = document.body;
               btn.classList.toggle("dark");
               if (btnText.innerHTML === "Normal Mode") {
                  btnText.innerHTML = "Dark Mode!";
               } else {
                  btnText.innerHTML = "Normal Mode";
            }}
      </script>
   </body>
</html>

本例輸出如下

 

更新於: 2021 年 2 月 10 日

542 次瀏覽

開啟您的 職業 生涯

完成課程,獲得認證

立即開始
廣告