16

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

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

暗模式滚动条:

暗模式滚动条

4

2 回答 2

36

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

目前支持 Chrome 81 和 Safari 13

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

: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>

于 2021-02-08T07:33:30.127 回答
2

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

btn.addEventListener("click", () => {
// https://stackoverflow.com/questions/65940522/how-do-i-switch-to-chromes-dark-scrollbar-like-github-does
            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>

于 2021-02-23T18:24:13.623 回答