如何使用 CSS 为网站创建暗/亮模式

cssweb developmentfront end technology更新于 2024/5/16 13:00:17

通过更改页面的文本颜色和背景颜色,我们可以为网站添加暗/亮模式。

语法

以下语法可用于应用暗模式。

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>

这将给出以下输出

 


相关文章


有用资源