如何像 GitHub 那样切换到 Chrome 深色滚动条?

How do I switch to Chromes dark scrollbar like GitHub does?

我刚发现,当您使用 GitHub 的深色模式时,GitHub 在 Chrome 中使用深色滚动条。如果切换颜色模式,滚动条也会随之切换。

我怎样才能实现这种行为?我找不到任何方法告诉浏览器使用深色模式。

深色模式滚动条:

是CSS属性color-scheme。这还将在表单控件、背景颜色和文本颜色上应用主题。

目前支持 Chrome 81、Firefox 96 和 Safari 13。

MDN 来源:https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme

注意:对于深色模式配色方案的 Firefox,正文背景颜色保持浅色主题,但其他表单元素采用深色主题。

:root {
  color-scheme: dark;
}

.container {
  padding: 25px;
  height: 2000px;
}
<div class="container">
  <div class="text">Dark Mode</div>
  <input type="text" placeholder="input with dark theme"/>
</div>

如果您想即时更改主题,那么您 运行 会遇到这样的问题,即滚动条在交互之前不会更新其配色方案。刷新滚动条的一种方法是更改​​其父溢出 属性,在本例中为 html 元素。

const btn = document.querySelector("button");
let isDark = true;

btn.addEventListener("click", () => {
  // remove scrollbars
  document.documentElement.style.overflow = "hidden";
  // trigger reflow so that overflow style is applied
  document.body.clientWidth;
  // change scheme
  document.documentElement.setAttribute(
    "data-color-scheme",
    isDark ? "light" : "dark"
  );
  // remove overflow style, which will bring back the scrollbar with the correct scheme 
  document.documentElement.style.overflow = "";

  isDark = !isDark;
});
[data-color-scheme="dark"] {
  color-scheme: dark;
}

[data-color-scheme="light"] {
  color-scheme: light;
}

.container {
  padding: 25px;
  height: 2000px;
 }
<html lang="en" data-color-scheme="dark">
<body>
  <div class="container">
    <button>Click to Change Color Scheme</button>
    <br>
    <br>
    <br>
    <input type="text" placeholder="dummy input">
  </div>
</body>
</html>

const btn = document.querySelector("button");
let isDark = true;

btn.addEventListener("click", () => {
// 
            document.documentElement.style.display = 'none';

            document.documentElement.setAttribute(
                "data-color-scheme",
                isDark  ? "dark" : "light"
            );
            // remove scrollbars
//                document.documentElement.style.overflow = "hidden";
            // trigger reflow so that overflow style is applied
            document.body.clientWidth;
            // remove overflow style, which will bring back the scrollbar with the correct scheme
//                document.documentElement.style.overflow = "";
            document.documentElement.style.display = '';

  isDark = !isDark;
});
[data-color-scheme="dark"] {
  color-scheme: dark;
}

[data-color-scheme="light"] {
  color-scheme: light;
}

.container {
  padding: 25px;
  height: 2000px;
 }
<html lang="en" data-color-scheme="dark">
<body>
  <div class="container">
    <button>Click to Change Color Scheme</button>
    <br>
    <br>
    <br>
    <input type="text" placeholder="dummy input">
  </div>
</body>
</html>